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

const term = (process.argv[2] || '').toLowerCase();
if (!term) { console.error('Usage: tsx scripts/find-contribuyente.ts <texto>'); process.exit(1); }

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: cols } = await pool.query(
      `SELECT column_name FROM information_schema.columns WHERE table_name='contribuyentes'`,
    );
    const colNames = cols.map((c: any) => c.column_name);
    const nameCols = colNames.filter(n => n.includes('nombre') || n.includes('razon'));
    const filterSql = nameCols.map(c => `LOWER(${c}) LIKE '%${term}%'`).join(' OR ');
    if (!filterSql) continue;
    const { rows } = await pool.query(`SELECT entidad_id, rfc, ${nameCols.join(',')} FROM contribuyentes WHERE ${filterSql}`);
    if (rows.length > 0) {
      console.log(`\n[${t.rfc}]`);
      for (const r of rows) console.log(r);
    }
  }
  await prisma.$disconnect();
}
main().catch(async e => { console.error(e); await prisma.$disconnect().catch(() => {}); process.exit(1); });
