import { readdirSync, readFileSync, statSync } from 'fs';
import { join } from 'path';
import { GUARDS_METADATA } from '@nestjs/common/constants';
import { REQUIRE_MODULE_KEY } from '../auth/decorators/require-module.decorator';
import { REQUIRE_PERMISSION_KEY } from '../auth/decorators/require-permission.decorator';
import { REQUIRE_SUBMODULO_KEY } from '../auth/decorators/require-submodulo.decorator';
import { ModuleGuard } from '../auth/guards/module.guard';
import { PermissionGuard } from '../auth/guards/permission.guard';
import { SubmoduloGuard } from '../auth/guards/submodulo.guard';
import { ImportacionesController } from './importaciones.controller';

/**
 * Permisos y submódulos por handler (plan Task 16, tabla de permisos de la Global, spec punto 2, F16) y el barrido de
 * códigos de error (D14, F23): ningún throw del módulo sin `codigo`.
 */
describe('ImportacionesController · permisos y submódulos', () => {
  const proto = ImportacionesController.prototype as any;
  const handlers = Object.getOwnPropertyNames(proto).filter((m) => m !== 'constructor' && typeof proto[m] === 'function');
  const permiso = (h: string) => Reflect.getMetadata(REQUIRE_PERMISSION_KEY, proto[h]);
  const submodulo = (h: string) => Reflect.getMetadata(REQUIRE_SUBMODULO_KEY, proto[h]);

  const EMB = 'IMP_EMBARQUES';
  const COS = 'IMP_COSTOS';
  const DES = 'IMP_DESPACHOS';
  const CFG = 'IMP_CONFIG';

  /** handler → [privilegio de IMPORTACIONES, submódulo]. Es la tabla de la Global; conceptos con IMP_COSTOS (F16). */
  const TABLA: Record<string, [string, string]> = {
    getConfig: ['IMP_CFG_CONFIG_VER', CFG],
    updateConfig: ['IMP_CFG_CONFIG_EDITAR', CFG],
    contexto: ['IMP_EMB_EMBARQUE_VER', EMB],
    findAll: ['IMP_EMB_EMBARQUE_VER', EMB],
    findOne: ['IMP_EMB_EMBARQUE_VER', EMB],
    getBitacora: ['IMP_EMB_EMBARQUE_VER', EMB],
    create: ['IMP_EMB_EMBARQUE_CREAR', EMB],
    update: ['IMP_EMB_EMBARQUE_EDITAR', EMB],
    updateEstado: ['IMP_EMB_EMBARQUE_EDITAR', EMB],
    addItem: ['IMP_EMB_EMBARQUE_EDITAR', EMB],
    updateItem: ['IMP_EMB_EMBARQUE_EDITAR', EMB],
    removeItem: ['IMP_EMB_EMBARQUE_EDITAR', EMB],
    remove: ['IMP_EMB_EMBARQUE_ELIMINAR', EMB],
    vistaLiberacion: ['IMP_EMB_EMBARQUE_CERRAR', EMB],
    liberarEmbarque: ['IMP_EMB_EMBARQUE_CERRAR', EMB],
    revertirLiberacion: ['IMP_EMB_EMBARQUE_CERRAR', EMB],
    cerrar: ['IMP_EMB_EMBARQUE_CERRAR', EMB],
    reabrir: ['IMP_EMB_EMBARQUE_CERRAR', EMB],
    sellar: ['IMP_EMB_EMBARQUE_CERRAR', EMB],
    reintegrarCierre: ['IMP_EMB_EMBARQUE_CERRAR', EMB],
    getConceptos: ['IMP_COS_COSTO_VER', COS],
    createConcepto: ['IMP_CFG_CONFIG_EDITAR', COS],
    updateConcepto: ['IMP_CFG_CONFIG_EDITAR', COS],
    removeConcepto: ['IMP_CFG_CONFIG_EDITAR', COS],
    addCosto: ['IMP_COS_COSTO_CREAR', COS],
    updateCosto: ['IMP_COS_COSTO_EDITAR', COS],
    removeCosto: ['IMP_COS_COSTO_EDITAR', COS],
    generarCxP: ['IMP_COS_COSTO_EDITAR', COS],
    reintegrarComponente: ['IMP_COS_COSTO_EDITAR', COS],
    getDespacho: ['IMP_DES_DESPACHO_VER', DES],
    revisionDespacho: ['IMP_DES_DESPACHO_VER', DES],
    createDespacho: ['IMP_DES_DESPACHO_CREAR', DES],
    updateDespacho: ['IMP_DES_DESPACHO_EDITAR', DES],
    removeDespacho: ['IMP_DES_DESPACHO_ELIMINAR', DES],
    confirmarDespacho: ['IMP_DES_DESPACHO_PROCESAR', DES],
    reintegrarContabilidadDespacho: ['IMP_DES_DESPACHO_PROCESAR', DES],
    listIsc: ['IMP_CFG_CONFIG_VER', CFG],
    createIsc: ['IMP_CFG_CONFIG_EDITAR', CFG],
    updateIsc: ['IMP_CFG_CONFIG_EDITAR', CFG],
    removeIsc: ['IMP_CFG_CONFIG_EDITAR', CFG],
  };

  it('la clase pide el módulo IMPORTACIONES con JWT, ModuleGuard, SubmoduloGuard y PermissionGuard (en ese orden)', () => {
    expect(Reflect.getMetadata(REQUIRE_MODULE_KEY, ImportacionesController)).toBe('IMPORTACIONES');
    const guards = Reflect.getMetadata(GUARDS_METADATA, ImportacionesController) as unknown[];
    expect(guards).toHaveLength(4);
    expect(guards.slice(1)).toEqual([ModuleGuard, SubmoduloGuard, PermissionGuard]);
  });

  it('cada handler declara permiso y submódulo de la tabla de la Global', () => {
    const real = Object.fromEntries(handlers.map((h) => [h, [permiso(h), submodulo(h)]]));
    const esperado = Object.fromEntries(Object.entries(TABLA).map(([h, [p, s]]) => [h, [{ modulo: 'IMPORTACIONES', privilegio: p }, s]]));
    expect(real).toEqual(esperado);
  });

  it('ningún handler sin permiso ni sin submódulo, y ninguno con guards propios (valen los de la clase)', () => {
    expect(handlers.filter((h) => !permiso(h) || !submodulo(h))).toEqual([]);
    expect(handlers.filter((h) => ((Reflect.getMetadata(GUARDS_METADATA, proto[h]) as unknown[] | undefined) ?? []).length > 0)).toEqual([]);
    expect(handlers.length).toBe(Object.keys(TABLA).length);
  });

  it('fila 25: abiertos (GET /embarques) con IMP_EMBARQUES y conceptos con IMP_COSTOS (Facturas, Gastos y Tesorería)', () => {
    expect([permiso('findAll').privilegio, submodulo('findAll')]).toEqual(['IMP_EMB_EMBARQUE_VER', EMB]);
    expect([permiso('getConceptos').privilegio, submodulo('getConceptos')]).toEqual(['IMP_COS_COSTO_VER', COS]);
    for (const h of ['createConcepto', 'updateConcepto', 'removeConcepto']) expect([permiso(h).privilegio, submodulo(h)]).toEqual(['IMP_CFG_CONFIG_EDITAR', COS]);
  });
});

// ─────────────────────────── Barrido de códigos (F23) ───────────────────────────

const RAIZ = join(__dirname, '..', '..');

function archivosTs(dir: string): string[] {
  return readdirSync(dir).flatMap((n) => {
    const ruta = join(dir, n);
    if (statSync(ruta).isDirectory()) return n === '__tests__' ? [] : archivosTs(ruta);
    return n.endsWith('.ts') && !n.endsWith('.spec.ts') ? [ruta] : [];
  });
}

/** Índice del cierre que corresponde a la apertura en `desde` (paréntesis, llaves o corchetes; salta strings). */
function cierre(src: string, desde: number): number {
  const pares: Record<string, string> = { '(': ')', '{': '}', '[': ']' };
  const pila: string[] = [];
  for (let i = desde; i < src.length; i++) {
    const c = src[i];
    if (c === "'" || c === '"' || c === '`') {
      for (i++; i < src.length && src[i] !== c; i++) if (src[i] === '\\') i++;
      continue;
    }
    if (pares[c]) pila.push(pares[c]);
    else if (c === pila[pila.length - 1]) {
      pila.pop();
      if (pila.length === 0) return i;
    }
  }
  throw new Error(`Sin cierre desde ${desde}`);
}

/** Cuerpo del método `nombre` de una clase (desde su `{` hasta su `}`). */
function cuerpoDeMetodo(src: string, nombre: string): string {
  const m = new RegExp(`\\n\\s+(?:private |public )?(?:async )?${nombre}\\(`).exec(src);
  if (!m) throw new Error(`No encontré el método ${nombre}`);
  const finParams = cierre(src, m.index + m[0].length - 1);
  const abre = src.indexOf('{', finParams);
  return src.slice(abre, cierre(src, abre) + 1);
}

/**
 * ¿El objeto literal tiene la CLAVE `codigo` (`codigo: x` o la abreviada `{ codigo }` / `, codigo`)? Se borra antes el
 * contenido de los strings: un `message: 'sin codigo: …'` no cuenta.
 */
function tieneClaveCodigo(objeto: string): boolean {
  const sinStrings = objeto.replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`/g, "''");
  return /[{,]\s*codigo\s*(?::|,|\})/.test(sinStrings);
}

/**
 * Excepciones sin `codigo`: `new (BadRequest|NotFound|Conflict)Exception(x)` cuyo primer argumento no es un objeto literal
 * con `codigo` (un string, un template literal o una variable pasan desapercibidos con una regex simple), y los objetos de
 * `solicitudInvalida`/`conflicto`/`noEncontrado` sin `codigo` (un spread de un error ya armado vale).
 */
function throwsSinCodigo(src: string): string[] {
  const malos: string[] = [];
  const re = /new (?:BadRequest|NotFound|Conflict)Exception\(|\b(?:solicitudInvalida|conflicto|noEncontrado)\(/g;
  for (let m = re.exec(src); m; m = re.exec(src)) {
    const abre = m.index + m[0].length - 1;
    const args = src.slice(abre + 1, cierre(src, abre)).trim();
    const esNew = m[0].startsWith('new ');
    const objeto = args.startsWith('{') ? args.slice(0, cierre(args, 0) + 1) : null;
    const ok = objeto !== null && (tieneClaveCodigo(objeto) || (!esNew && /^\{\s*\.\.\./.test(objeto)));
    // A los helpers el tipo `ErrorEstructurado` ya les exige `codigo`: una variable tipada pasa (es la de `errorImp`).
    if (!ok && !(!esNew && /^[A-Za-z_$][\w$]*$/.test(args))) malos.push(src.slice(m.index, Math.min(src.length, abre + 80)).replace(/\s+/g, ' '));
  }
  return malos;
}

describe('Importaciones · ningún throw del módulo sin codigo (D14, F23)', () => {
  it('el detector marca string, template literal y variable; deja pasar el objeto con codigo', () => {
    expect(throwsSinCodigo("throw new NotFoundException('No existe');")).toHaveLength(1);
    expect(throwsSinCodigo('throw new BadRequestException(`Criterio ${c}`);')).toHaveLength(1);
    expect(throwsSinCodigo('const msg = "x"; throw new ConflictException(msg);')).toHaveLength(1);
    expect(throwsSinCodigo("throw solicitudInvalida({ message: 'x', campo: 'y' });")).toHaveLength(1);
    // Falso negativo de la regex por palabra: «codigo» solo dentro del texto del message.
    expect(throwsSinCodigo("throw new BadRequestException({ message: 'sin codigo: revisar' });")).toHaveLength(1);
    expect(throwsSinCodigo("throw new BadRequestException({ message: 'x', codigo_viejo: 'A' });")).toHaveLength(1);
    expect(throwsSinCodigo("throw new ConflictException({ message: 'x', codigo });")).toEqual([]);
    expect(throwsSinCodigo("throw new ConflictException({ codigo, message: 'x' });")).toEqual([]);
    expect(throwsSinCodigo("throw new BadRequestException({ message: 'x', codigo: 'X' });")).toEqual([]);
    expect(throwsSinCodigo('throw solicitudInvalida({ ...primero, errores });')).toEqual([]);
    expect(throwsSinCodigo("throw errorImp(CODIGOS_IMP.X, 'y');")).toEqual([]);
  });

  it('src/importaciones (servicios, reglas y controller) no tiene throws sin código', () => {
    const malos = archivosTs(join(RAIZ, 'src', 'importaciones')).flatMap((f) => throwsSinCodigo(readFileSync(f, 'utf8')).map((t) => `${f.slice(RAIZ.length + 1)}: ${t}`));
    expect(malos).toEqual([]);
  });

  it.each([
    ['src/compras/compras.service.ts', 'crearComponenteImportacion'],
    ['src/gastos/gastos.service.ts', 'crearComponenteImportacion'],
    ['src/gastos/gastos.service.ts', 'anularEnTx'],
  ])('%s · %s (conversión de un costo y anulación que apaga el componente) no tiene throws sin código', (archivo, metodo) => {
    expect(throwsSinCodigo(cuerpoDeMetodo(readFileSync(join(RAIZ, archivo), 'utf8'), metodo))).toEqual([]);
  });
});
