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

const RFC = 'TOAH680201RA2';

async function main() {
  const tenants = await prisma.tenant.findMany({ select: { id: true, rfc: true, databaseName: true } });
  for (const t of tenants) {
    let pool;
    try { pool = await tenantDb.getPool(t.id, t.databaseName); } catch { continue; }
    const { rows } = await pool.query(`
      SELECT tipo_comprobante, metodo_pago, cfdi_tipo_relacion, COUNT(*)::int AS cnt
        FROM cfdis
       WHERE (UPPER(rfc_emisor) = $1 OR UPPER(rfc_receptor) = $1)
         AND status NOT IN ('Cancelado','0')
         AND cfdi_tipo_relacion IS NOT NULL
       GROUP BY tipo_comprobante, metodo_pago, cfdi_tipo_relacion
       ORDER BY cnt DESC`,
      [RFC]);
    if (rows.length === 0) continue;
    console.log(`\n=== ${t.rfc} (${RFC}) ===`);
    for (const r of rows) {
      console.log(`  ${r.tipo_comprobante}/${r.metodo_pago || '?'}/rel=${r.cfdi_tipo_relacion}: ${r.cnt}`);
    }
  }
  await prisma.$disconnect();
}
main().catch(async e => { console.error(e); await prisma.$disconnect().catch(() => {}); process.exit(1); });
