import type pg from 'pg';
import { sendTransactionalEmail } from '../../notifications/infrastructure/settings-email-provider.js';

interface CashCloseReport {
  sessionId: string;
  storeId: string;
  terminalId: string;
  openedAt: Date;
  closedAt: Date;
  userId: string;
  financial: {
    openingCashCents: number;
    closingCashCents: number;
    actualCashCents: number;
    expectedCashCents: number;
    differenceCents: number;
  };
  sales: {
    totalCount: number;
    completedCount: number;
    completedTotalCents: number;
    pendingCount: number;
    refundedCount: number;
    refundedTotalCents: number;
    byState: Record<string, { count: number; totalCents: number }>;
  };
  payments: Array<{
    methodCode: string;
    methodName: string;
    totalCents: number;
    transactionCount: number;
  }>;
  items: {
    soldCount: number;
    uniqueProducts: number;
  };
}

function fmt(cents: number): string {
  return (cents / 100).toFixed(2) + ' \u20ac';
}

function fmtDate(d: Date): string {
  return new Date(d).toLocaleString('es-ES', {
    day: '2-digit', month: '2-digit', year: 'numeric',
    hour: '2-digit', minute: '2-digit',
  });
}

function tr(label: string, value: string): string {
  return `<tr><td style="padding:4px 8px;border-bottom:1px solid #eee;font-size:14px">${label}</td>` +
    `<td style="padding:4px 8px;border-bottom:1px solid #eee;font-size:14px;text-align:right;font-weight:bold">${value}</td></tr>`;
}

function htmlTable(rows: Array<{ label: string; value: string }>): string {
  return `<table style="border-collapse:collapse;width:100%;max-width:400px">` +
    rows.map(r => tr(r.label, r.value)).join('') +
    `</table>`;
}

export function buildCashCloseHtml(report: CashCloseReport): string {
  const { financial, sales, payments, items, openedAt, closedAt } = report;

  const rows: Array<{ label: string; value: string }> = [
    { label: 'Sesión abierta', value: fmtDate(openedAt) },
    { label: 'Sesión cerrada', value: fmtDate(closedAt) },
    { label: '', value: '' },
    { label: 'Saldo inicial', value: fmt(financial.openingCashCents) },
    { label: 'Ventas completadas', value: fmt(financial.expectedCashCents) },
    { label: 'Saldo esperado', value: fmt(financial.openingCashCents + financial.expectedCashCents) },
    { label: 'Efectivo real', value: fmt(financial.actualCashCents) },
    { label: 'Diferencia', value: fmt(financial.differenceCents) },
    { label: '', value: '' },
    { label: 'Ventas completadas', value: `${sales.completedCount} · ${fmt(sales.completedTotalCents)}` },
    { label: 'Ventas pendientes', value: String(sales.pendingCount) },
    { label: 'Ventas reembolsadas', value: `${sales.refundedCount} · ${fmt(sales.refundedTotalCents)}` },
    { label: 'Total líneas', value: String(sales.totalCount) },
    { label: 'Artículos vendidos', value: `${items.soldCount} (${items.uniqueProducts} productos)` },
  ];

  const paymentRows: Array<{ label: string; value: string }> = payments.map(p => ({
    label: p.methodName,
    value: `${fmt(p.totalCents)} (${p.transactionCount})`,
  }));

  return `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body style="font-family:Arial,sans-serif;background:#f5f5f5;margin:0;padding:20px">
<div style="max-width:600px;margin:0 auto;background:white;border-radius:8px;overflow:hidden;box-shadow:0 2px 8px rgba(0,0,0,.1)">
  <div style="background:#2D6A4F;padding:16px 24px">
    <h1 style="margin:0;color:white;font-size:20px">📊 Reporte de Cierre de Caja</h1>
  </div>
  <div style="padding:24px">
    <h2 style="margin:0 0 12px;font-size:16px;color:#333">Resumen financiero</h2>
    ${htmlTable(rows)}
    ${paymentRows.length > 0 ? `
    <h2 style="margin:24px 0 12px;font-size:16px;color:#333">Por forma de pago</h2>
    ${htmlTable(paymentRows)}` : ''}
  </div>
  <div style="padding:12px 24px;background:#f9f9f9;border-top:1px solid #eee;font-size:12px;color:#999;text-align:center">
    Generado automáticamente por Mercado de Vida · ${new Date().toLocaleString('es-ES')}
  </div>
</div>
</body>
</html>`;
}

export async function sendCashCloseReport(
  pool: pg.Pool,
  report: CashCloseReport,
): Promise<void> {
  const result = await pool.query<{ value: string }>(
    `SELECT value FROM store_settings WHERE key = 'smtp_report_email'`,
  );
  const to = result.rows[0]?.value?.trim();
  if (!to) {
    console.log('[cash-close-mailer] No report email configured, skipping.');
    return;
  }

  const subject = `Cierre de caja · ${new Date(report.closedAt).toLocaleDateString('es-ES')} · ${fmt(report.financial.actualCashCents)}`;

  await sendTransactionalEmail(pool, {
    to,
    subject,
    text: `Reporte de cierre de caja.\n\n` +
      `Saldo inicial: ${fmt(report.financial.openingCashCents)}\n` +
      `Ventas: ${fmt(report.financial.expectedCashCents)}\n` +
      `Efectivo real: ${fmt(report.financial.actualCashCents)}\n` +
      `Diferencia: ${fmt(report.financial.differenceCents)}\n` +
      `Artículos vendidos: ${report.items.soldCount}\n`,
    html: buildCashCloseHtml(report),
  });
  console.log(`[cash-close-mailer] Report sent to ${to}`);
}
