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

async function main() {
  const tenants = await prisma.tenant.findMany({ where: { active: true }, select: { id: true, rfc: true, databaseName: true } });
  for (const t of tenants) {
    const pool = await tenantDb.getPool(t.id, t.databaseName);
    // descubrir tablas con 'entidad' o 'contribuyente' en el nombre
    const { rows: tbls } = await pool.query(`SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND (table_name LIKE '%entidad%' OR table_name LIKE '%contribuyente%') ORDER BY table_name`);
    console.log(`\n[${t.rfc}] tablas:`, tbls.map((r: any) => r.table_name).join(', '));

    // Join con rfcs si existe
    try {
      const { rows } = await pool.query(
        `SELECT c.entidad_id, c.rfc, r.razon_social, c.regimen_fiscal, c.codigo_postal
           FROM contribuyentes c
           LEFT JOIN rfcs r ON UPPER(r.rfc) = UPPER(c.rfc)
          ORDER BY r.razon_social NULLS LAST, c.rfc`,
      );
      for (const r of rows) console.log(' ', r);
    } catch (e: any) {
      console.log('  ERR:', e.message);
    }
  }
  await prisma.$disconnect();
}
main().catch(async e => { console.error(e); await prisma.$disconnect().catch(() => {}); process.exit(1); });
