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

const uuid = (process.argv[2] || '5c874749-748f-11f0-96b1-2b9310891836').toLowerCase();

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 } = await pool.query(
      `SELECT
        c.uuid, c.total_mxn,
        COALESCE((
          SELECT SUM(COALESCE(p.monto_pago_mxn, 0))
          FROM cfdis p
          WHERE p.tipo_comprobante = 'P'
            AND LOWER(COALESCE(p.uuid_relacionado, '')) LIKE '%' || LOWER(c.uuid) || '%'
            AND p.status NOT IN ('Cancelado', '0')
        ), 0) AS pagos_p,
        COALESCE((
          SELECT SUM(COALESCE(e.total_mxn, 0))
          FROM cfdis e
          WHERE e.tipo_comprobante = 'E'
            AND COALESCE(e.cfdi_tipo_relacion, '') <> '07'
            AND e.cfdis_relacionados IS NOT NULL
            AND LOWER(c.uuid) = ANY(string_to_array(LOWER(e.cfdis_relacionados), '|'))
            AND e.status NOT IN ('Cancelado', '0')
        ), 0) AS ncs,
        CASE WHEN c.cfdi_tipo_relacion = '07' AND c.cfdis_relacionados IS NOT NULL THEN
          COALESCE((
            SELECT SUM(COALESCE(a.total_mxn, 0))
            FROM cfdis a
            WHERE LOWER(a.uuid) = ANY(string_to_array(LOWER(c.cfdis_relacionados), '|'))
              AND a.status NOT IN ('Cancelado', '0')
          ), 0) ELSE 0 END AS anticipo_aplicado,
        (
          COALESCE(c.total_mxn, 0)
          - COALESCE((SELECT SUM(COALESCE(p.monto_pago_mxn, 0)) FROM cfdis p
              WHERE p.tipo_comprobante = 'P'
                AND LOWER(COALESCE(p.uuid_relacionado, '')) LIKE '%' || LOWER(c.uuid) || '%'
                AND p.status NOT IN ('Cancelado', '0')), 0)
          - COALESCE((SELECT SUM(COALESCE(e.total_mxn, 0)) FROM cfdis e
              WHERE e.tipo_comprobante = 'E' AND COALESCE(e.cfdi_tipo_relacion,'') <> '07'
                AND e.cfdis_relacionados IS NOT NULL
                AND LOWER(c.uuid) = ANY(string_to_array(LOWER(e.cfdis_relacionados), '|'))
                AND e.status NOT IN ('Cancelado','0')), 0)
          - CASE WHEN c.cfdi_tipo_relacion = '07' AND c.cfdis_relacionados IS NOT NULL THEN
              COALESCE((SELECT SUM(COALESCE(a.total_mxn,0)) FROM cfdis a
                WHERE LOWER(a.uuid) = ANY(string_to_array(LOWER(c.cfdis_relacionados),'|'))
                  AND a.status NOT IN ('Cancelado','0')), 0)
            ELSE 0 END
        ) AS saldo_computado
      FROM cfdis c WHERE LOWER(c.uuid) = $1`,
      [uuid],
    );
    if (rows.length === 0) continue;
    console.log(`[${t.rfc}]`, rows[0]);
  }
  await prisma.$disconnect();
}
main().catch(async (e) => { console.error(e); await prisma.$disconnect().catch(() => {}); process.exit(1); });
