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

const leer = (carpeta: string) =>
  readFileSync(join(__dirname, '../../prisma/migrations', carpeta, 'migration.sql'), 'utf8').replace(/--.*$/gm, '');
const bloquesDo = (sql: string): string[] => sql.match(/DO \$\$[\s\S]*?END \$\$;/g) ?? [];
const sinIds = (sql: string) =>
  expect(sql).not.toMatch(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i);

describe('migración 20261023100000_oc_permisos', () => {
  const sql = leer('20261023100000_oc_permisos');
  const bloques = bloquesDo(sql);
  const inserts = sql.match(/INSERT INTO [\s\S]*?;/g) ?? [];
  const [ver, operar, aprobar, facturaRecepcion] = inserts;
  const operaCompras = /\(ms\.codigo = 'COMPRAS' OR mp\.codigo = 'COMPRAS'\)/;

  it('va en un solo DO $$ con cuatro INSERT en perfiles_privilegios y avisa los conteos con RAISE NOTICE', () => {
    expect(bloques).toHaveLength(1);
    expect(sql.replace(bloques[0], '').trim()).toBe('');
    expect(inserts).toHaveLength(4);
    inserts.forEach((i) =>
      expect(i).toMatch(/^INSERT INTO perfiles_privilegios \(perfil_id, privilegio_id, modulo_id, active\)/),
    );
    ['ver', 'operar', 'aprobar', 'factura_recepcion'].forEach((v) =>
      expect(bloques[0]).toContain(`GET DIAGNOSTICS ${v} = ROW_COUNT;`),
    );
    expect(bloques[0]).toMatch(/RAISE NOTICE '[^']*', ver, operar, aprobar, factura_recepcion;/);
  });

  it('permisos: a1/a2/a3 con NOT EXISTS y sin ids', () => {
    sinIds(sql);
    expect(sql).not.toMatch(/\b(UPDATE|DELETE|TRUNCATE|DROP|ALTER)\b/i);
    expect(sql).not.toMatch(/\bpf\.perfil\b|razon_social/);
    inserts.forEach((i) => {
      expect(i).toMatch(/NOT EXISTS \(\s*SELECT 1 FROM perfiles_privilegios x/);
      expect(i).toMatch(/x\.privilegio_id = pr\.id/);
      expect(i).toMatch(/x\.modulo_id = compras\.id/);
      expect(i).toMatch(/x\.active = true/);
      expect(i).toMatch(/JOIN modulos compras ON compras\.codigo = 'COMPRAS'/);
    });
    // a1: VER a todo perfil con algún privilegio activo de COMPRAS, sin mirar la acción.
    expect(ver).toMatch(/pr\.codigo = 'CMP_OC_ORDEN_COMPRA_VER'/);
    expect(ver).toMatch(operaCompras);
    expect(ver).not.toMatch(/accion/);
    expect(ver).not.toMatch(/_CREAR|_EDITAR|_ELIMINAR|_APROBAR/);
    // a2: CREAR / EDITAR / ELIMINAR a quien crea, edita o elimina algo de COMPRAS.
    expect(operar).toContain(
      "pr.codigo IN ('CMP_OC_ORDEN_COMPRA_CREAR', 'CMP_OC_ORDEN_COMPRA_EDITAR', 'CMP_OC_ORDEN_COMPRA_ELIMINAR')",
    );
    expect(operar).toMatch(operaCompras);
    expect(operar).toMatch(/AND p\.accion IN \('CREAR', 'EDITAR', 'ELIMINAR'\)/);
    ['VER', 'EXPORTAR', 'APROBAR', 'PAGAR', 'ANULAR'].forEach((a) => expect(operar).not.toContain(`'${a}'`));
    expect(operar).not.toMatch(/_VER'|_APROBAR'/);
    // a3: APROBAR a quien ya aprueba algo de COMPRAS.
    expect(aprobar).toMatch(/pr\.codigo = 'CMP_OC_ORDEN_COMPRA_APROBAR'/);
    expect(aprobar).toMatch(operaCompras);
    expect(aprobar).toMatch(/AND p\.accion = 'APROBAR'/);
    // Orden: VER, operar, aprobar, factura/recepción.
    expect(sql.indexOf(operar)).toBeGreaterThan(sql.indexOf(ver));
    expect(sql.indexOf(aprobar)).toBeGreaterThan(sql.indexOf(operar));
    expect(sql.indexOf(facturaRecepcion)).toBeGreaterThan(sql.indexOf(aprobar));
  });

  it('b: VER a quien tiene CMP_FAC_FACTURA_PROV_CREAR o algún CMP_REC_RECEPCION_*, en cualquier módulo', () => {
    expect(facturaRecepcion).toMatch(/pr\.codigo = 'CMP_OC_ORDEN_COMPRA_VER'/);
    expect(facturaRecepcion).toMatch(
      /p\.codigo = 'CMP_FAC_FACTURA_PROV_CREAR' OR p\.codigo LIKE 'CMP\\_REC\\_RECEPCION\\_%'/,
    );
    // Sin filtro por módulo: cubre el privilegio grabado con otro modulo_id.
    expect(facturaRecepcion).not.toMatch(operaCompras);
    expect(facturaRecepcion).not.toMatch(/_CREAR'\)|_EDITAR|_ELIMINAR|_APROBAR/);
  });

  it('nombra exactamente los códigos de privilegio del criterio', () => {
    const codigos = new Set(sql.match(/'(CMP_OC_\w+|CMP_FAC_\w+)'/g));
    expect([...codigos].sort()).toEqual(
      [
        "'CMP_FAC_FACTURA_PROV_CREAR'",
        "'CMP_OC_ORDEN_COMPRA_APROBAR'",
        "'CMP_OC_ORDEN_COMPRA_CREAR'",
        "'CMP_OC_ORDEN_COMPRA_EDITAR'",
        "'CMP_OC_ORDEN_COMPRA_ELIMINAR'",
        "'CMP_OC_ORDEN_COMPRA_VER'",
      ].sort(),
    );
  });
});

describe('migración 20261023100100_oc_moneda_obligatoria', () => {
  const sql = leer('20261023100100_oc_moneda_obligatoria');
  const updates = sql.match(/UPDATE [\s\S]*?;/g) ?? [];
  const bloques = bloquesDo(sql);

  it('moneda: UPDATE con la principal, NOT NULL dentro de DO $$ con RAISE', () => {
    expect(updates).toHaveLength(1);
    const [u] = updates;
    expect(u).toMatch(/^UPDATE orden_compra_cab oc/);
    expect(u).toMatch(
      /SET moneda_id = \(\s*SELECT em\.moneda_id FROM empresa_monedas em\s+WHERE em\.empresa_id = oc\.empresa_id AND em\.es_principal = true\s+LIMIT 1\s*\)/,
    );
    expect(u).toMatch(/WHERE oc\.moneda_id IS NULL/);
    // Solo las que tienen principal: si no, el SET dejaría NULL igual y el DO $$ lo cuenta.
    expect(u).toMatch(
      /AND EXISTS \(\s*SELECT 1 FROM empresa_monedas em2\s+WHERE em2\.empresa_id = oc\.empresa_id AND em2\.es_principal = true\s*\)/,
    );

    expect(bloques).toHaveLength(1);
    const b = bloques[0];
    expect(sql.indexOf(b)).toBeGreaterThan(sql.indexOf(u));
    expect(b).toMatch(/SELECT count\(\*\) INTO \w+ FROM orden_compra_cab WHERE moneda_id IS NULL;/);
    expect(b).toMatch(/RAISE EXCEPTION '[^']*%[^']*', \w+;/);
    expect(b.indexOf('RAISE EXCEPTION')).toBeLessThan(b.indexOf('SET NOT NULL'));
    expect(b).toContain('ALTER TABLE orden_compra_cab ALTER COLUMN moneda_id SET NOT NULL;');
  });

  it('no usa "PYG" ni ids y no borra nada', () => {
    sinIds(sql);
    expect(sql).not.toMatch(/PYG/);
    expect(sql).not.toMatch(/\b(DELETE|TRUNCATE|DROP)\b/i);
  });
});
