/**
 * PayIn Queries — BRL→USD transactions (br_transaction_to_usa)
 * Agent-level and admin-level transaction fetching
 */
const { pool, parseDate } = require('./helpers');

async function fetchTransacoes(agenteId) {
  const conn = await pool.getConnection();
  try {
    const [rowsBrlUsd] = await conn.execute(`
      SELECT DISTINCT
        c.nome                                             AS cliente,
        t.created_at                                       AS data_operacao,
        t.amount_brl                                       AS valor_reais,
        t.amount_usd                                       AS valor_dolar,
        t.iof                                              AS iof_pct,
        ROUND(t.iof / 100 * t.amount_usd * t.exchange_rate, 2) AS iof_valor_rs,
        ROUND(t.ptax, 4)                                   AS taxa_ptax,
        ROUND(t.exchange_rate, 4)                           AS taxa_cobrada,
        ROUND(t.exchange_rate - t.ptax, 4)                  AS spread_bruto,
        ROUND((t.exchange_rate - t.ptax) / t.exchange_rate * 100, 2) AS spread_pct,
        t.status
      FROM br_transaction_to_usa t
      INNER JOIN ag_contas ac ON ac.conta_id = t.id_conta AND ac.agente_id = ?
      INNER JOIN conta c ON c.id_conta = t.id_conta
      ORDER BY t.created_at
    `, [agenteId]);

    const [rowsUsdBrl] = await conn.execute(`
      SELECT DISTINCT
        c.nome                                             AS cliente,
        p.created_at                                       AS data_operacao,
        ROUND(p.valor * p.cotacao, 2)                      AS valor_reais,
        p.valor                                            AS valor_dolar,
        0                                                  AS iof_pct,
        0                                                  AS iof_valor_rs,
        ROUND(p.ptax, 4)                                   AS taxa_ptax,
        ROUND(p.cotacao, 4)                                AS taxa_cobrada,
        ROUND(p.ptax - p.cotacao, 4)                       AS spread_bruto,
        CASE WHEN p.cotacao > 0 THEN ROUND((p.ptax - p.cotacao) / p.ptax * 100, 2) ELSE 0 END AS spread_pct,
        p.pgto                                             AS status
      FROM pagamento_br p
      INNER JOIN conta c ON c.id_conta = p.id_conta
      INNER JOIN ag_contas ac ON ac.conta_id = p.id_conta AND ac.agente_id = ?
      ORDER BY p.created_at
    `, [agenteId]);

    return { rowsBrlUsd, rowsUsdBrl };
  } finally {
    conn.release();
  }
}

function serialize(rowsBrlUsd, rowsUsdBrl) {
  const dataBrlUsd = rowsBrlUsd.map(r => ({
    fluxo: 'BRL → USD',
    cliente: r.cliente,
    data_operacao: parseDate(r.data_operacao),
    data_sort: parseDate(r.data_operacao) || '',
    valor_reais: Number(r.valor_reais),
    valor_dolar: Number(r.valor_dolar),
    iof_pct: Number(r.iof_pct),
    iof_valor_rs: Number(r.iof_valor_rs),
    taxa_ptax: Number(r.taxa_ptax),
    taxa_cobrada: Number(r.taxa_cobrada),
    spread_bruto: Number(r.spread_bruto),
    spread_pct: Number(r.spread_pct),
    status: r.status,
  }));

  const dataUsdBrl = rowsUsdBrl.map(r => ({
    fluxo: 'USD → BRL',
    cliente: r.cliente,
    data_operacao: parseDate(r.data_operacao),
    data_sort: parseDate(r.data_operacao) || '',
    valor_reais: Number(r.valor_reais),
    valor_dolar: Number(r.valor_dolar),
    iof_pct: Number(r.iof_pct),
    iof_valor_rs: Number(r.iof_valor_rs),
    taxa_ptax: Number(r.taxa_ptax),
    taxa_cobrada: Number(r.taxa_cobrada),
    spread_bruto: Number(r.spread_bruto),
    spread_pct: Number(r.spread_pct),
    status: r.status,
  }));

  return [...dataBrlUsd, ...dataUsdBrl].sort((a, b) => a.data_sort.localeCompare(b.data_sort));
}

// Fetch ALL transactions (for admin) - with date filter for performance
async function fetchAllTransacoes(diasAtras = 90) {
  const conn = await pool.getConnection();
  try {
    const [rowsBrlUsd] = await conn.execute(`
      SELECT
        c.nome                                             AS cliente,
        t.created_at                                       AS data_operacao,
        t.amount_brl                                       AS valor_reais,
        t.amount_usd                                       AS valor_dolar,
        t.iof                                              AS iof_pct,
        ROUND(t.iof / 100 * t.amount_usd * t.exchange_rate, 2) AS iof_valor_rs,
        ROUND(t.ptax, 4)                                   AS taxa_ptax,
        ROUND(t.exchange_rate, 4)                           AS taxa_cobrada,
        ROUND(t.exchange_rate - t.ptax, 4)                  AS spread_bruto,
        ROUND((t.exchange_rate - t.ptax) / t.exchange_rate * 100, 2) AS spread_pct,
        t.status
      FROM br_transaction_to_usa t
      INNER JOIN conta c ON c.id_conta = t.id_conta
      WHERE t.created_at >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
      ORDER BY t.created_at DESC
    `, [diasAtras]);

    const [rowsUsdBrl] = await conn.execute(`
      SELECT
        c.nome                                             AS cliente,
        p.created_at                                       AS data_operacao,
        ROUND(p.valor * p.cotacao, 2)                      AS valor_reais,
        p.valor                                            AS valor_dolar,
        0                                                  AS iof_pct,
        0                                                  AS iof_valor_rs,
        ROUND(p.ptax, 4)                                   AS taxa_ptax,
        ROUND(p.cotacao, 4)                                AS taxa_cobrada,
        ROUND(p.ptax - p.cotacao, 4)                       AS spread_bruto,
        CASE WHEN p.cotacao > 0 THEN ROUND((p.ptax - p.cotacao) / p.ptax * 100, 2) ELSE 0 END AS spread_pct,
        p.pgto                                             AS status
      FROM pagamento_br p
      INNER JOIN conta c ON c.id_conta = p.id_conta
      WHERE p.created_at >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
      ORDER BY p.created_at DESC
    `, [diasAtras]);

    return { rowsBrlUsd, rowsUsdBrl };
  } finally {
    conn.release();
  }
}

module.exports = {
  fetchTransacoes,
  serialize,
  fetchAllTransacoes
};
