import { prisma, tenantDb } from '../src/config/database.js';

const RFC_CARLOS = 'TORC9611214CA';

async function main() {
  const tenants = await prisma.tenant.findMany({
    select: { id: true, rfc: true, databaseName: true },
  });

  let found = false;

  for (const t of tenants) {
    let pool;
    try {
      pool = await tenantDb.getPool(t.id, t.databaseName);
    } catch {
      continue;
    }

    const { rows: contribs } = await pool.query(
      `SELECT c.entidad_id, c.rfc, c.regimen_fiscal, e.nombre, fo.facturapi_org_id, fo.csd_uploaded, fo.active AS org_active
         FROM contribuyentes c
         JOIN entidades_gestionadas e ON e.id = c.entidad_id
         LEFT JOIN facturapi_orgs fo ON fo.contribuyente_id = c.entidad_id
        WHERE UPPER(c.rfc) = $1`,
      [RFC_CARLOS],
    );
    if (contribs.length === 0) continue;

    found = true;
    console.log(`\n=== Tenant ${t.rfc} — BD ${t.databaseName} ===`);
    for (const c of contribs) {
      console.log(`Contribuyente Carlos: ${c.entidad_id}`);
      console.log(`  nombre=${c.nombre}`);
      console.log(`  regimen_fiscal (CSV)=${c.regimen_fiscal}`);
      console.log(`  facturapi_org_id=${c.facturapi_org_id || 'NULL (sin org)'}`);
      console.log(`  csd_uploaded=${c.csd_uploaded}  org_active=${c.org_active}`);
    }

    const { rows: cfdis } = await pool.query(
      `SELECT uuid, type, tipo_comprobante, metodo_pago, total, total_mxn,
              rfc_emisor, rfc_receptor, nombre_receptor, status, fecha_emision,
              source, facturapi_id
         FROM cfdis
        WHERE UPPER(rfc_emisor) = $1
          AND (source = 'facturapi' OR facturapi_id IS NOT NULL OR fecha_emision >= NOW() - interval '2 days')
        ORDER BY fecha_emision DESC
        LIMIT 10`,
      [RFC_CARLOS],
    );

    console.log(`\nÚltimas ${cfdis.length} facturas (facturapi o recientes) emitidas por ${RFC_CARLOS}:`);
    for (const c of cfdis) {
      console.log(`  UUID=${c.uuid}`);
      console.log(`    tipo=${c.tipo_comprobante} mp=${c.metodo_pago} status=${c.status} source=${c.source}`);
      console.log(`    receptor=${c.rfc_receptor} (${c.nombre_receptor})`);
      console.log(`    total=${c.total} total_mxn=${c.total_mxn}`);
      console.log(`    fecha_emision=${c.fecha_emision?.toISOString?.() || c.fecha_emision}`);
      console.log(`    facturapi_id=${c.facturapi_id}`);
    }

    const { rows: [anyEmitido] } = await pool.query(
      `SELECT COUNT(*)::int AS total,
              SUM(CASE WHEN source='facturapi' THEN 1 ELSE 0 END)::int AS via_facturapi,
              SUM(CASE WHEN source='facturapi' AND status NOT IN ('Cancelado','0') THEN 1 ELSE 0 END)::int AS vigentes
         FROM cfdis
        WHERE UPPER(rfc_emisor) = $1`,
      [RFC_CARLOS],
    );
    console.log(`\nResumen total CFDIs con rfc_emisor=${RFC_CARLOS}:`);
    console.log(`  total=${anyEmitido.total}  via_facturapi=${anyEmitido.via_facturapi}  vigentes_facturapi=${anyEmitido.vigentes}`);
  }

  if (!found) {
    console.log(`\nNo se encontró contribuyente con RFC ${RFC_CARLOS} en ningún tenant.`);
  }

  await prisma.$disconnect();
}

main().catch(async e => {
  console.error(e);
  await prisma.$disconnect().catch(() => {});
  process.exit(1);
});
