/**
 * Shared SQL fragments, revenue formulas, and utility functions
 * Used across all query modules to eliminate duplication
 */
const pool = require('../db-rds');

// --- Utility Functions ---

function parseDate(d) {
  try {
    if (!d) return null;
    const dt = d instanceof Date ? d : new Date(d);
    return isNaN(dt.getTime()) ? null : dt.toISOString().slice(0, 16).replace('T', ' ');
  } catch (e) { return null; }
}

function fmtDate(d) {
  return d instanceof Date ? d.toISOString().slice(0, 10) : String(d).slice(0, 10);
}

function fmtDateTime(d) {
  try {
    const dt = d instanceof Date ? d : new Date(d);
    return dt.toISOString().slice(0, 16).replace('T', ' ');
  } catch (e) { return String(d); }
}

/**
 * Calculate previous period dates for comparison
 */
function calcPrevPeriod(dataInicio, dataFim) {
  const start = new Date(dataInicio);
  const end = new Date(dataFim);
  const periodDays = Math.round((end - start) / (1000 * 60 * 60 * 24)) + 1;
  const prevEnd = new Date(start);
  prevEnd.setDate(prevEnd.getDate() - 1);
  const prevStart = new Date(prevEnd);
  prevStart.setDate(prevStart.getDate() - periodDays + 1);
  return {
    prevStartStr: prevStart.toISOString().slice(0, 10),
    prevEndStr: prevEnd.toISOString().slice(0, 10),
    periodDays
  };
}

// --- Reusable SQL Fragments ---

// BRL→USD spread revenue formula (per-row)
const SQL_BRLUSD_SPREAD_REVENUE = `(exchange_rate - ptax) / exchange_rate * amount_usd`;

// BRL→USD average spread percentage
const SQL_BRLUSD_SPREAD_PCT = `(exchange_rate - ptax) / exchange_rate * 100`;

// USD→BRL spread revenue formula (per-row)
const SQL_USDBRL_SPREAD_REVENUE = `(ptax - cotacao) / ptax * valor`;

// USD→BRL average spread percentage
const SQL_USDBRL_SPREAD_PCT = `CASE WHEN cotacao > 0 THEN (ptax - cotacao) / ptax * 100 ELSE 0 END`;

// USD→BRL filter: real currency exchange (not balance)
const SQL_USDBRL_FILTER = `cotacao IS NOT NULL AND cotacao > 0 AND (pgto IS NULL OR pgto != 'balance')`;

// USD→USD filter: balance or no cotacao
const SQL_USDUSD_FILTER = `(cotacao IS NULL OR cotacao = 0 OR pgto = 'balance')`;

// BR→US Revenue formula (real P&L per transaction)
const SQL_BRUS_REVENUE = `(
  (
    ROUND((t.amount_brl - IF(pm.provider IN ('ouribank','bs2'), 0, t.fee)) / t.ptax, 2)
    - COALESCE(t.pfee, 0)
  ) - (
    t.amount_usd + COALESCE(t.bonus_valor, 0) - COALESCE(t.taxa_cr, 0)
  )
)`;

// BR→US valid provider filter
const SQL_BRUS_PROVIDER_FILTER = `pm.provider IN ('dlocal','bexs','braza','bs2','ouribank','msb')`;

// BR→US valid transaction status filter
const SQL_BRUS_STATUS_FILTER = `(t.status IN ('boleto_pago','finalizado') OR t.date_sent_usa <> '0000-00-00 00:00:00')`;

// Standard completed status for br_transaction_to_usa
const SQL_COMPLETED_STATUSES = `('boleto_pago','finalizado')`;

// Format trend rows (common across all query modules)
function fmtTrendRows(rows) {
  return rows.map(r => ({
    dia: fmtDate(r.dia),
    qtd: Number(r.qtd),
    vol_usd: Number(r.vol_usd),
    avg_spread: Number(r.avg_spread) || 0
  }));
}

module.exports = {
  pool,
  parseDate,
  fmtDate,
  fmtDateTime,
  calcPrevPeriod,
  fmtTrendRows,
  SQL_BRLUSD_SPREAD_REVENUE,
  SQL_BRLUSD_SPREAD_PCT,
  SQL_USDBRL_SPREAD_REVENUE,
  SQL_USDBRL_SPREAD_PCT,
  SQL_USDBRL_FILTER,
  SQL_USDUSD_FILTER,
  SQL_BRUS_REVENUE,
  SQL_BRUS_PROVIDER_FILTER,
  SQL_BRUS_STATUS_FILTER,
  SQL_COMPLETED_STATUSES
};
