// billdeskpg/utils/billdeskClient.js
const axios = require('axios');
const { processRequest } = require('./apirequestmodule');
const { encryptAndSign, verifyAndDecrypt } = require('./symjose');
const { processResponse } = require('./apiresponsemodule');

async function callBilldesk({ path, payload, clientId, encKey, sigKey }) {
  const base = process.env.BD_BASE_URL;
  const url = base.endsWith('/') ? `${base}${path}` : `${base}/${path}`;

  const { headers, body: plaintext } = processRequest(JSON.stringify(payload));

  // encrypt + sign
  const joseEnvelope = await encryptAndSign(plaintext, clientId, encKey, sigKey);

  const resp = await axios.post(url, joseEnvelope, {
    headers,
    timeout: 30000,
    validateStatus: () => true
  });

  if (resp.status !== 200) {
    let detail = resp.data;
    if (typeof resp.data === 'string' && resp.data.includes('.')) {
      try {
        const decryptedErr = await verifyAndDecrypt(resp.data, encKey, null, sigKey, null);
        detail = JSON.parse(decryptedErr);
      } catch (e) {
        // keep raw
      }
    }
    const err = new Error('BillDesk API call failed');
    err.status = resp.status;
    err.detail = detail;
    throw err;
  }

  const decrypted = await verifyAndDecrypt(resp.data, encKey, null, sigKey, null);
  const parsed = processResponse(decrypted);
  return parsed;
}

module.exports = { callBilldesk };
