const axios = require('axios');
const { MD5 } = require('crypto-js');
const SystemConfigService = require('../services/systemConfig.service');

async function uploadCardTSR(userId, telco, code, serial, amount, command) {
    try {
        // Lấy config TSR từ DB, fallback về .env
        const cfg = await SystemConfigService.getConfig();
        const PARTNER_KEY = cfg.tsrPartnerKey || process.env.PARTNER_KEY_TST;
        const PARTNER_ID = cfg.tsrPartnerId || process.env.PARTNER_ID_TST;
        const URL_TSR = cfg.tsrUrl || process.env.URL_TSR;

        let sign = MD5(PARTNER_KEY + code + serial).toString();
        const formData = new FormData();
        formData.append('telco', telco);
        formData.append('code', code);
        formData.append('serial', serial);
        formData.append('amount', amount);
        formData.append('request_id', userId);
        formData.append('partner_id', PARTNER_ID);
        formData.append('command', command);
        formData.append('partner_key', PARTNER_KEY);
        formData.append('sign', sign);

        const response = await axios.post(URL_TSR, formData);
        return response.data;
    } catch (error) {
        console.log(error);
    }
}

module.exports = uploadCardTSR;
