/**
 * Inspect the shape of the response from Facturapi invoices.retrieve
 * for a recent emission, to know what fields are actually populated.
 */
import { prisma, tenantDb } from '../src/config/database.js';
import { env } from '../src/config/env.js';

const CONTRIB_ID = '414b22a8-c6e2-4f39-be0f-7537a848107e';
const TENANT_RFC = 'DESPACHO_MO3NI6U8_B9VGG';
const INVOICE_ID = '69ebc61f87f122486514c3b4'; // latest

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

  // Fetch org API key
  const { rows } = await pool.query<{ facturapi_org_id: string }>(
    `SELECT facturapi_org_id FROM facturapi_orgs WHERE contribuyente_id=$1 AND active=true`,
    [CONTRIB_ID],
  );
  if (rows.length === 0) {
    console.log('No facturapi_org_id found');
    return;
  }
  const orgId = rows[0].facturapi_org_id;

  // Get the org's API key (HTTP direct because SDK has issues)
  const userKey = env.FACTURAPI_USER_KEY;
  const keyRes = await fetch(`https://www.facturapi.io/v2/organizations/${orgId}/apikeys/test`, {
    headers: { Authorization: `Bearer ${userKey}` },
  });
  const keyData = await keyRes.json();
  const apiKey = typeof keyData === 'string' ? keyData : keyData.apikey || keyData.key;

  // Retrieve the invoice
  const invRes = await fetch(`https://www.facturapi.io/v2/invoices/${INVOICE_ID}`, {
    headers: { Authorization: `Bearer ${apiKey}` },
  });
  const invoice = await invRes.json();

  console.log('=== FACTURAPI INVOICE RESPONSE ===');
  console.log('Top-level keys:', Object.keys(invoice).sort().join(', '));
  console.log('');
  console.log('invoice.id =', invoice.id);
  console.log('invoice.uuid =', invoice.uuid);
  console.log('invoice.date =', invoice.date);
  console.log('invoice.subtotal =', invoice.subtotal);
  console.log('invoice.total =', invoice.total);
  console.log('invoice.series =', invoice.series);
  console.log('invoice.folio_number =', invoice.folio_number);
  console.log('invoice.issuer =', JSON.stringify(invoice.issuer, null, 2));
  console.log('invoice.issuer_info =', JSON.stringify(invoice.issuer_info, null, 2));
  console.log('invoice.issuer_type =', invoice.issuer_type);
  console.log('invoice.organization =', JSON.stringify(invoice.organization, null, 2));
  console.log('invoice.customer =', JSON.stringify(invoice.customer, null, 2));
  console.log('invoice.taxes =', JSON.stringify(invoice.taxes, null, 2));
  console.log('invoice.items =', JSON.stringify(invoice.items?.slice(0, 2), null, 2));

  await prisma.$disconnect();
}

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