import { env } from "../../config/env";
const forcedFailAll = String(env.MQTT_PUBLISH_FORCE_FAIL_ALL).toLowerCase() === "true";
const forcedFailDevices = new Set(String(env.MQTT_PUBLISH_FORCE_FAIL_DEVICE_IDS)
    .split(",")
    .map((item) => item.trim())
    .filter(Boolean));
function shouldForceFail(deviceId) {
    return forcedFailAll || forcedFailDevices.has(deviceId);
}
export function buildPaymentSuccessPayload(input) {
    const displayAmount = `${input.amount.toLocaleString("id-ID")}`;
    return {
        message_type: "payment_success",
        device_id: input.device_id,
        event_id: input.event_id,
        transaction_id: input.transaction_id,
        merchant_id: input.merchant_id,
        merchant_name: input.merchant_name,
        amount: input.amount,
        currency: input.currency,
        paid_at: input.paid_at,
        partner_reference: input.partner_reference,
        audio_text: `Pembayaran diterima ${input.currency} ${displayAmount}`,
        display_text: `Pembayaran diterima Rp${displayAmount}`
    };
}
export function makePaymentSuccessTopic(deviceId) {
    return `devices/${deviceId}/downlink/payment/success`;
}
export function makeDynamicQrResponseTopic(deviceId) {
    return `devices/${deviceId}/downlink/dynamic-qr/response`;
}
export function makeConfigPushTopic(deviceId) {
    return `devices/${deviceId}/downlink/config/push`;
}
async function publishMqttPayload(deviceId, topic, payload) {
    const publishedAt = new Date().toISOString();
    if (shouldForceFail(deviceId)) {
        return {
            ok: false,
            topic,
            qos: 1,
            retained: false,
            publishedAt,
            reason: "MQTT_PUBLISH_SIMULATED_FAILURE",
            payload
        };
    }
    return {
        ok: true,
        topic,
        qos: 1,
        retained: false,
        publishedAt,
        payload
    };
}
export async function publishPaymentSuccess(payload) {
    return publishMqttPayload(payload.device_id, makePaymentSuccessTopic(payload.device_id), payload);
}
export async function publishDynamicQrResponse(deviceId, payload) {
    return publishMqttPayload(deviceId, makeDynamicQrResponseTopic(deviceId), payload);
}
export async function publishConfigPush(deviceId, payload) {
    return publishMqttPayload(deviceId, makeConfigPushTopic(deviceId), payload);
}
