/**
 * Aplica la migración 042 (ncs_emitidas + ncs_recibidas) a todos los tenants.
 * Idempotente — ADD COLUMN IF NOT EXISTS no falla si ya existe.
 */
import { prisma, tenantDb } from '../src/config/database.js';
import { migrate } from '../src/config/tenant-migrations.js';

async function main() {
  const tenants = await prisma.tenant.findMany({
    where: { active: true },
    select: { id: true, rfc: true, databaseName: true, nombre: true },
    orderBy: { rfc: 'asc' },
  });

  console.log(`Aplicando migraciones a ${tenants.length} tenants...\n`);

  let ok = 0;
  let failed = 0;

  for (const t of tenants) {
    try {
      const pool = await tenantDb.getPool(t.id, t.databaseName);
      await migrate(pool);
      console.log(`✓ ${t.rfc.padEnd(25)} ${t.nombre}`);
      ok++;
    } catch (err: any) {
      console.error(`✗ ${t.rfc.padEnd(25)} ${t.nombre} → ${err.message || err}`);
      failed++;
    }
  }

  console.log(`\nCompletado: ${ok} OK, ${failed} fallidos`);
  await prisma.$disconnect();
  process.exit(failed > 0 ? 1 : 0);
}

main().catch(e => { console.error(e); process.exit(1); });
