import { readFileSync } from 'fs';
import { join } from 'path';

const leer = (carpeta: string) =>
  readFileSync(join(__dirname, '../../prisma/migrations', carpeta, 'migration.sql'), 'utf8').replace(/--.*$/gm, '');

describe('migración 20261029100000_requisiciones_precio_referencia', () => {
  const sql = leer('20261029100000_requisiciones_precio_referencia');
  it('precio_referencia: ADD COLUMN IF NOT EXISTS y UPDATE con IS DISTINCT FROM', () => {
    expect(sql).toMatch(/ALTER TABLE requisicion_det ADD COLUMN IF NOT EXISTS costo_referencia DECIMAL\(18, 4\)/);
    expect(sql).toMatch(/ALTER TABLE requisicion_cab ADD COLUMN IF NOT EXISTS total_para_aprobacion DECIMAL\(18, 2\) DEFAULT 0/);
    expect(sql).toMatch(/SET total_para_aprobacion = c\.total_estimado/);
    expect(sql).toMatch(/total_para_aprobacion IS DISTINCT FROM c\.total_estimado/);
    expect(sql).toContain('RAISE NOTICE');
  });
  it('solo toca requisiciones sin ninguna línea con costo_referencia (NOT EXISTS): idempotente', () => {
    expect(sql).toMatch(/NOT EXISTS \(\s*SELECT 1 FROM requisicion_det d\s+WHERE d\.requisicion_id = c\.id AND d\.costo_referencia IS NOT NULL\s*\)/);
    expect(sql).not.toMatch(/\b(DELETE|TRUNCATE|DROP)\b/i);
  });
});

describe('migración 20261029100100_requisiciones_numero_unico', () => {
  const sql = leer('20261029100100_requisiciones_numero_unico');
  it('numero_unico: RAISE EXCEPTION si hay repetidos e índice IF NOT EXISTS', () => {
    expect(sql).toMatch(/numero_requisicion IS NOT NULL/);
    expect(sql).toMatch(/HAVING count\(\*\) > 1/);
    expect(sql).toMatch(/IF repetidos > 0 THEN\s+RAISE EXCEPTION '[^']*%[^']*', repetidos;/);
    expect(sql).toMatch(
      /CREATE UNIQUE INDEX IF NOT EXISTS uk_requisicion_cab_empresa_numero ON requisicion_cab \(empresa_id, numero_requisicion\);/,
    );
    expect(sql).not.toMatch(/\b(UPDATE|DELETE|TRUNCATE|DROP)\b/i);
  });
});

describe('migración 20261029100200_requisiciones_pendientes_a_borrador', () => {
  const sql = leer('20261029100200_requisiciones_pendientes_a_borrador');
  it('por criterio, sin ids: pendientes a borrador con el historial antes del borrado', () => {
    expect(sql).toMatch(/estado = 'pendiente_aprobacion'/);
    expect(sql).not.toMatch(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/);
    const insert = sql.indexOf('INSERT INTO requisicion_historial');
    const del = sql.indexOf('DELETE FROM requisicion_aprobacion');
    expect(insert).toBeGreaterThanOrEqual(0);
    expect(del).toBeGreaterThan(insert);
    expect(sql.indexOf('UPDATE requisicion_cab')).toBeGreaterThan(del);
  });
  it('el evento: accion vuelta_a_borrador_precio_estimado, usuario_id y comentario null, datos con los niveles aprobados', () => {
    expect(sql).toContain("'vuelta_a_borrador_precio_estimado'");
    expect(sql).toMatch(/'pendiente_aprobacion',\s*'borrador',\s*NULL,\s*NULL/);
    expect(sql).toMatch(/jsonb_agg\(/);
    expect(sql).toMatch(/a\.estado = 'aprobada'/);
    for (const campo of ['nivel', 'perfil_id', 'aprobado_por', 'fecha_resuelta']) expect(sql).toContain(`'${campo}'`);
    expect(sql).toContain('RAISE NOTICE');
  });
});

describe('migración 20261029100300_requisiciones_recalcular_ejecutado', () => {
  const sql = leer('20261029100300_requisiciones_recalcular_ejecutado');
  it('recalcular: sin ids, IS DISTINCT FROM, excluye anulados, convierte con la cotización, no toca canceladas ni rechazadas', () => {
    // Por criterio: ningún id ni nombre.
    expect(sql).not.toMatch(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/);
    expect(sql).not.toMatch(/\b(DELETE|TRUNCATE|DROP|INSERT)\b/i);
    expect(sql).toMatch(/DO \$\$/);
    // Facturas y gastos no anulados, atados a la línea.
    expect(sql).toMatch(/FROM compra_det cd\s+JOIN compra_cab cc ON cc\.id = cd\.compra_id/);
    expect(sql).toMatch(/FROM gasto_det gd\s+JOIN gasto_cab gc ON gc\.id = gd\.gasto_id/);
    expect(sql).toMatch(/COALESCE\(cc\.anulado, false\) = false/);
    expect(sql).toMatch(/COALESCE\(gc\.anulado, false\) = false/);
    // Fuera de PYG: subtotal × cotización del documento, a 2 decimales (ítem por ítem, como ejecucion-requisicion.ts).
    expect(sql).toMatch(/ROUND\(COALESCE\(cd\.subtotal, 0\) \* COALESCE\(NULLIF\(cc\.cotizacion, 0\), 1\), 2\)/);
    expect(sql).toMatch(/ROUND\(COALESCE\(gd\.subtotal, 0\) \* COALESCE\(NULLIF\(gc\.cotizacion, 0\), 1\), 2\)/);
    expect(sql).toMatch(/upper\(trim\(m\.codigo\)\) = 'PYG'/);
    // Líneas: solo donde cambia; no las de canceladas ni rechazadas.
    expect(sql).toMatch(/UPDATE requisicion_det d/);
    expect(sql).toMatch(/c\.estado NOT IN \('cancelada', 'rechazada'\)/);
    for (const col of ['cantidad_ejecutada', 'monto_ejecutado', 'estado']) {
      expect(sql).toMatch(new RegExp(`d\\.${col} IS DISTINCT FROM n\\.`));
    }
    // Cabecera: solo aprobada / ejecutada parcial / ejecutada total, y solo donde cambia.
    expect(sql).toMatch(/UPDATE requisicion_cab c/);
    expect(sql).toMatch(/c\.estado IN \('aprobada', 'ejecutada_parcial', 'ejecutada_total'\)/);
    expect(sql).toMatch(/c\.total_ejecutado IS DISTINCT FROM t\.total/);
    expect(sql).toMatch(/c\.estado IS DISTINCT FROM t\.estado/);
    // El orden: primero las líneas, después las cabeceras.
    expect(sql.indexOf('UPDATE requisicion_cab')).toBeGreaterThan(sql.indexOf('UPDATE requisicion_det'));
    expect(sql.match(/RAISE NOTICE/g)?.length).toBeGreaterThanOrEqual(2);
  });
});

describe('migración 20261029100400_requisiciones_permisos', () => {
  const sql = leer('20261029100400_requisiciones_permisos');
  it('permisos: a1–a4 con NOT EXISTS, sin ids, sin UPDATE/DELETE, con RAISE NOTICE', () => {
    expect(sql).not.toMatch(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/);
    expect(sql).not.toMatch(/\b(UPDATE|DELETE|TRUNCATE|DROP)\b/i);
    expect(sql.match(/INSERT INTO perfiles_privilegios/g)).toHaveLength(4);
    expect(sql.match(/NOT EXISTS/g)).toHaveLength(4);
    expect(sql.match(/RAISE NOTICE/g)).toHaveLength(4);
    expect(sql.match(/ms\.codigo = 'COMPRAS' OR mp\.codigo = 'COMPRAS'/g)).toHaveLength(3);
    expect(sql.match(/JOIN modulos compras ON compras\.codigo = 'COMPRAS'/g)).toHaveLength(4);
  });
  it('a1 _VER a todo perfil de COMPRAS; a2 _CREAR/_EDITAR/_ELIMINAR por acción; a3 _APROBAR por acción; a4 VER y APROBAR de los perfiles de niveles', () => {
    expect(sql).toMatch(/pr\.codigo IN \('CMP_REQ_REQUISICION_VER'\)|pr\.codigo = 'CMP_REQ_REQUISICION_VER'/);
    expect(sql).toMatch(/p\.accion IN \('CREAR', 'EDITAR', 'ELIMINAR'\)/);
    for (const c of ['CREAR', 'EDITAR', 'ELIMINAR']) expect(sql).toContain(`'CMP_REQ_REQUISICION_${c}'`);
    expect(sql).toMatch(/p\.accion = 'APROBAR'/);
    expect(sql).toMatch(/pr\.codigo = 'CMP_REQ_REQUISICION_APROBAR'/);
    expect(sql).toMatch(/FROM requisicion_aprobacion_config/);
    expect(sql).toMatch(/pr\.codigo IN \('CMP_REQ_REQUISICION_VER', 'CMP_REQ_REQUISICION_APROBAR'\)/);
  });
  it('p.active y pp.active filtran el origen', () => {
    expect(sql).toMatch(/pp\.active = true\s+AND p\.active = true/);
  });
});
