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

async function main() {
  const tenant = await prisma.tenant.findFirst({
    where: { rfc: 'DESPACHO_MO3NI6U8_B9VGG' },
    select: { id: true, databaseName: true },
  });
  if (!tenant) return;
  const pool = await tenantDb.getPool(tenant.id, tenant.databaseName);

  const { rows } = await pool.query(
    `SELECT * FROM rfcs WHERE id IN (23709, 1) ORDER BY id`,
  );
  for (const r of rows) {
    console.log(`\nrfcs id=${r.id}:`);
    for (const k of Object.keys(r).sort()) {
      console.log(`  ${k} = ${r[k]}`);
    }
  }

  // Also look at all 4 Facturapi CFDIs' emisor fields
  const { rows: all4 } = await pool.query(
    `SELECT uuid, rfc_emisor, nombre_emisor, rfc_emisor_id, regimen_fiscal_emisor,
            rfc_receptor, nombre_receptor, subtotal, total, xml_original IS NULL AS no_xml
       FROM cfdis WHERE source='facturapi' ORDER BY fecha_emision DESC`,
  );
  console.log(`\n=== Todas las CFDIs source=facturapi (${all4.length}) ===`);
  for (const r of all4) {
    console.log(`  ${r.uuid} | emisor='${r.rfc_emisor}' (id=${r.rfc_emisor_id}, nombre='${r.nombre_emisor}', regimen=${r.regimen_fiscal_emisor})`);
    console.log(`    receptor='${r.rfc_receptor}' (${r.nombre_receptor})  subtotal=${r.subtotal} total=${r.total} xml_missing=${r.no_xml}`);
  }

  await prisma.$disconnect();
}

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