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

const rawRfc = process.argv[2];
if (!rawRfc) {
  console.error('Usage: tsx scripts/inspect-rfc.ts <rfc>');
  process.exit(1);
}
const rfc = rawRfc.toUpperCase();

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);

    const { rows: contrib } = await pool.query(
      `SELECT * FROM contribuyentes WHERE UPPER(rfc) = $1`,
      [rfc],
    );
    if (contrib.length > 0) {
      console.log(`\n[${t.rfc}] Contribuyente ${rfc}:`);
      console.log(contrib[0]);
    }

    const { rows: rfcEntry } = await pool.query(
      `SELECT id, rfc, razon_social, regimen_fiscal, codigo_postal FROM rfcs WHERE UPPER(rfc) = $1`,
      [rfc],
    );
    if (rfcEntry.length > 0) {
      console.log(`[${t.rfc}] rfcs table:`, rfcEntry[0]);
    }

    if (contrib.length > 0) {
      const { rows: org } = await pool.query(
        `SELECT facturapi_org_id, csd_uploaded, active FROM facturapi_orgs WHERE contribuyente_id = $1`,
        [contrib[0].entidad_id],
      );
      if (org.length > 0) console.log(`[${t.rfc}] facturapi_orgs:`, org[0]);
    }
  }

  await prisma.$disconnect();
}

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