import { prisma, tenantDb } from '../src/config/database.js';
import { env } from '../src/config/env.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);

  // 1. Last CSF stored for Carlos (source of truth on what SAT sees)
  const { rows: csfs } = await pool.query(
    `SELECT rfc, created_at, datos->'regimenes' AS regimenes, datos->'obligaciones' AS obligaciones,
            datos->>'estatusPadron' AS estatus, datos->>'fechaInicioOperaciones' AS fecha_inicio,
            datos->'domicilio' AS domicilio
       FROM constancias_situacion_fiscal
      WHERE UPPER(rfc) = 'TORC9611214CA'
      ORDER BY created_at DESC LIMIT 1`,
  );
  console.log(`\n=== CSF más reciente de Carlos ===`);
  if (csfs.length === 0) {
    console.log('NO HAY CSF descargada para este RFC. Eso explica el error de LCO si el contribuyente no ha sincronizado con SAT.');
  } else {
    const c = csfs[0];
    console.log(`created_at:         ${c.created_at}`);
    console.log(`estatusPadron:      ${c.estatus}`);
    console.log(`fechaInicioOper:    ${c.fecha_inicio}`);
    console.log(`Regímenes (CSF):`);
    if (Array.isArray(c.regimenes)) for (const r of c.regimenes) console.log(' ', r);
    console.log(`Obligaciones (CSF):`);
    if (Array.isArray(c.obligaciones)) for (const o of c.obligaciones) console.log(' ', o);
  }

  // 2. Contribuyente data en BD (lo que estamos usando para llenar la org)
  const { rows: contrib } = await pool.query(
    `SELECT c.entidad_id, c.rfc, r.razon_social, c.regimen_fiscal, c.codigo_postal, c.domicilio
       FROM contribuyentes c
       LEFT JOIN rfcs r ON UPPER(r.rfc) = UPPER(c.rfc)
      WHERE UPPER(c.rfc) = 'TORC9611214CA'`,
  );
  console.log(`\n=== Contribuyente en BD ===`);
  console.log(contrib[0]);

  // 3. Facturapi org actual (lo que Facturapi está enviando al SAT)
  const { rows: org } = await pool.query(
    `SELECT facturapi_org_id FROM facturapi_orgs WHERE contribuyente_id = $1 AND active = true`,
    [contrib[0]?.entidad_id],
  );
  if (org.length > 0 && env.FACTURAPI_USER_KEY) {
    const res = await fetch(`https://www.facturapi.io/v2/organizations/${org[0].facturapi_org_id}`, {
      headers: { 'Authorization': `Bearer ${env.FACTURAPI_USER_KEY}` },
    });
    if (res.ok) {
      const o = await res.json() as any;
      console.log(`\n=== Facturapi Organization ===`);
      console.log(`orgId:         ${o.id}`);
      console.log(`name:          ${o.name}`);
      console.log(`legal:`);
      console.log(`  legal_name:  ${o.legal?.legal_name}`);
      console.log(`  tax_system:  ${o.legal?.tax_system}`);
      console.log(`  name:        ${o.legal?.name}`);
      console.log(`  address:     ${JSON.stringify(o.legal?.address)}`);
      console.log(`certificate:`);
      console.log(`  has_certificate:  ${o.certificate?.has_certificate}`);
      console.log(`  serial_number:    ${o.certificate?.serial_number}`);
      console.log(`  valid_until:      ${o.certificate?.valid_until}`);
    } else {
      console.log(`Facturapi GET failed: ${res.status}`);
    }
  }

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