const https = require('https');

const SEPAY_API_BASE = "https://my.sepay.vn/userapi";
const SEPAY_QR_BASE = "https://qr.sepay.vn/img";

/**
 * Helper to make HTTPS GET requests
 */
function get(url, headers = {}) {
  return new Promise((resolve, reject) => {
    https.get(url, { headers }, (res) => {
      let data = '';
      res.on('data', (chunk) => data += chunk);
      res.on('end', () => {
        try {
          resolve(JSON.parse(data));
        } catch (e) {
          resolve(null);
        }
      });
    }).on('error', (err) => reject(err));
  });
}

/**
 * Fetch transactions from SePay
 */
async function getTransactions(apiToken, params = {}) {
  const query = new URLSearchParams(params).toString();
  const url = `${SEPAY_API_BASE}/transactions/list?${query}`;
  const headers = {
    'Authorization': `Bearer ${apiToken}`,
    'Content-Type': 'application/json'
  };

  try {
    const data = await get(url, headers);
    if (data && data.status === 200) {
      return data.transactions || [];
    }
    return [];
  } catch (e) {
    console.error('[SePay Error] getTransactions:', e);
    return [];
  }
}

/**
 * Find a transaction matching content keyword and amount
 */
async function findTransactionByContent(apiToken, { contentKeyword, amount, accountNumber, hoursBack = 48, usedTxnIds = [] }) {
  const dateMin = new Date(Date.now() - hoursBack * 60 * 60 * 1000).toISOString().replace('T', ' ').split('.')[0];
  
  const params = {
    limit: 100,
    transaction_date_min: dateMin
  };
  
  if (accountNumber) params.account_number = accountNumber;
  if (amount) params.amount_in = amount;

  try {
    const transactions = await getTransactions(apiToken, params);
    const keywordUpper = contentKeyword.toUpperCase().trim();

    for (const txn of transactions) {
      const txnId = String(txn.id || '');
      if (usedTxnIds.includes(txnId)) continue;

      const txnContent = (txn.transaction_content || '').toUpperCase();
      const txnAmountIn = parseFloat(txn.amount_in || 0);

      if (txnContent.includes(keywordUpper) && txnAmountIn > 0) {
        if (amount && Math.abs(txnAmountIn - amount) > 1) continue;
        return txn;
      }
    }
    return null;
  } catch (e) {
    console.error('[SePay Error] findTransactionByContent:', e);
    return null;
  }
}

/**
 * Generate SePay QR URL
 */
function generateQrUrl({ accountNumber, bankShortName, amount, content }) {
  let url = `${SEPAY_QR_BASE}?acc=${accountNumber}&bank=${bankShortName}`;
  if (amount && amount > 0) url += `&amount=${Math.floor(amount)}`;
  if (content) url += `&des=${encodeURIComponent(content)}`;
  return url;
}

module.exports = {
  getTransactions,
  findTransactionByContent,
  generateQrUrl
};
