/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/utils/addonExtratoExport.js
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
*/

import { htmlToPdfDownload } from '@/services/pdf.service';

// ─── labels ─────────────────────────────────────────────────────────────────

const MOVEMENT_LABELS = {
    purchase: 'Compra',
    consumption: 'Consumo',
    adjustment: 'Ajuste',
    refund: 'Reembolso',
    bonus: 'Bônus',
    expiration: 'Expiração'
};

const ADDON_LABELS = {
    sms: 'SMS',
    email: 'E-mail',
    server: 'Servidor',
    domain: 'Domínio'
};

// ─── formatadores ───────────────────────────────────────────────────────────

function fmtDate(iso) {
    if (!iso) return '';
    try {
        return new Date(iso).toLocaleString('pt-BR', {
            day: '2-digit',
            month: '2-digit',
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
    } catch {
        return '';
    }
}

function fmtAmount(row) {
    const amt = Number(row.amount) || 0;
    if (row.type === 'purchase' || row.type === 'bonus' || row.type === 'refund') {
        return `+${amt}`;
    }
    if (row.type === 'consumption') {
        return `-${Math.abs(amt)}`;
    }
    return amt >= 0 ? `+${amt}` : `${amt}`;
}

function fmtBRL(cents) {
    if (!cents) return '';
    return (cents / 100).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
}

function addonLabel(type) {
    return ADDON_LABELS[type] || type || '';
}

function movementLabel(type) {
    return MOVEMENT_LABELS[type] || type || '';
}

// ─── sanitização para CSV ───────────────────────────────────────────────────

function csvCell(value) {
    if (value === null || value === undefined) return '';
    const s = String(value)
        .replace(/[\r\n]+/g, ' ')
        .replace(/"/g, '""')
        .trim();
    // Previne CSV injection: prefixa com espaço se começar com =, +, -, @
    const safe = /^[=+\-@]/.test(s) ? ' ' + s : s;
    return `"${safe}"`;
}

function csvLine(cells) {
    return cells.map(csvCell).join(';');
}

// ─── export CSV ─────────────────────────────────────────────────────────────

export function buildExtratoCSV(rows, summary, periodLabel) {
    const header = ['Data', 'Addon', 'Tipo', 'Quantidade', 'Saldo após', 'Descrição', 'Valor (R$)', 'Método', 'Referência'];

    const lines = [csvLine(header)];
    for (const r of rows) {
        lines.push(
            csvLine([
                fmtDate(r.created_at),
                addonLabel(r.addon_type),
                movementLabel(r.type),
                fmtAmount(r),
                r.balance_after ?? '',
                r.description ?? '',
                r.price_cents ? fmtBRL(r.price_cents) : '',
                r.payment_method ?? '',
                r.payment_reference ?? ''
            ])
        );
    }

    // Rodapé com resumo
    lines.push('');
    lines.push(csvLine(['Período', periodLabel, '', '', '', '', '', '', '']));
    lines.push(csvLine(['Registros', summary.totalRows, '', '', '', '', '', '', '']));
    lines.push(csvLine(['Total comprado (créditos)', summary.purchasedCredits, '', '', '', '', '', '', '']));
    lines.push(csvLine(['Total comprado (R$)', fmtBRL(summary.purchasedCents), '', '', '', '', '', '', '']));
    lines.push(csvLine(['Total consumido (créditos)', summary.consumedCredits, '', '', '', '', '', '', '']));

    return '\uFEFF' + lines.join('\r\n');
}

export function downloadExtratoCSV(rows, summary, periodLabel, filename) {
    const csv = buildExtratoCSV(rows, summary, periodLabel);
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename || `extrato-addons-${Date.now()}.csv`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// ─── export PDF ─────────────────────────────────────────────────────────────

function htmlEscape(s) {
    if (s === null || s === undefined) return '';
    return String(s)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}

function buildExtratoHTML(rows, summary, periodLabel, tenantName) {
    const tbody = rows
        .map(
            (r) => `
        <tr>
            <td>${htmlEscape(fmtDate(r.created_at))}</td>
            <td>${htmlEscape(addonLabel(r.addon_type))}</td>
            <td>${htmlEscape(movementLabel(r.type))}</td>
            <td class="num">${htmlEscape(fmtAmount(r))}</td>
            <td class="num">${htmlEscape(r.balance_after ?? '')}</td>
            <td>${htmlEscape(r.description ?? '')}</td>
            <td class="num">${htmlEscape(r.price_cents ? fmtBRL(r.price_cents) : '')}</td>
            <td>${htmlEscape(r.payment_reference ?? '')}</td>
        </tr>
    `
        )
        .join('');

    return `<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<title>Extrato de Recursos Extras</title>
<style>
    * { box-sizing: border-box; }
    body { font-family: 'Segoe UI', Arial, sans-serif; color: #1a1a1a; margin: 0; padding: 24px; font-size: 11px; }
    h1 { font-size: 18px; margin: 0 0 4px 0; color: #2e3440; }
    .subtitle { color: #6b7280; font-size: 11px; margin-bottom: 16px; }
    .summary { display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 16px; }
    .card { flex: 1 1 150px; border: 1px solid #e5e7eb; border-radius: 6px; padding: 8px 12px; background: #f9fafb; }
    .card .label { font-size: 9px; color: #6b7280; text-transform: uppercase; letter-spacing: 0.5px; }
    .card .value { font-size: 14px; font-weight: 600; color: #111827; margin-top: 2px; }
    table { width: 100%; border-collapse: collapse; font-size: 10px; }
    th { background: #374151; color: #fff; padding: 6px 8px; text-align: left; font-weight: 600; }
    td { padding: 5px 8px; border-bottom: 1px solid #e5e7eb; }
    td.num { text-align: right; font-variant-numeric: tabular-nums; }
    tr:nth-child(even) td { background: #f9fafb; }
    .footer { margin-top: 16px; font-size: 9px; color: #9ca3af; text-align: center; }
</style>
</head>
<body>
    <h1>Extrato de Recursos Extras</h1>
    <div class="subtitle">
        ${htmlEscape(tenantName || '')} &middot; Período: <strong>${htmlEscape(periodLabel)}</strong> &middot;
        Gerado em ${htmlEscape(fmtDate(new Date().toISOString()))}
    </div>

    <div class="summary">
        <div class="card"><div class="label">Registros</div><div class="value">${summary.totalRows}</div></div>
        <div class="card"><div class="label">Comprado (créditos)</div><div class="value">${summary.purchasedCredits}</div></div>
        <div class="card"><div class="label">Comprado (R$)</div><div class="value">${htmlEscape(fmtBRL(summary.purchasedCents) || 'R$ 0,00')}</div></div>
        <div class="card"><div class="label">Consumido (créditos)</div><div class="value">${summary.consumedCredits}</div></div>
    </div>

    <table>
        <thead>
            <tr>
                <th>Data</th>
                <th>Addon</th>
                <th>Tipo</th>
                <th class="num">Qtd.</th>
                <th class="num">Saldo após</th>
                <th>Descrição</th>
                <th class="num">Valor</th>
                <th>Referência</th>
            </tr>
        </thead>
        <tbody>
            ${tbody || '<tr><td colspan="8" style="text-align:center;color:#9ca3af;padding:16px;">Sem transações no período</td></tr>'}
        </tbody>
    </table>

    <div class="footer">AgênciaPSI &middot; Extrato de débitos e créditos de recursos extras</div>
</body>
</html>`;
}

export async function downloadExtratoPDF(rows, summary, periodLabel, tenantName, filename) {
    const html = buildExtratoHTML(rows, summary, periodLabel, tenantName);
    await htmlToPdfDownload(html, filename || `extrato-addons-${Date.now()}.pdf`);
}

// ─── util exposto pra página ────────────────────────────────────────────────

export const formatters = {
    fmtDate,
    fmtAmount,
    fmtBRL,
    addonLabel,
    movementLabel
};
