import { BadRequestException, NotFoundException, PipeTransform, RequestMethod } from '@nestjs/common';
import { GUARDS_METADATA, METHOD_METADATA, PATH_METADATA, ROUTE_ARGS_METADATA } from '@nestjs/common/constants';
import { REQUIRE_PERMISSION_KEY } from '../auth/decorators/require-permission.decorator';
import { AlgunPrivilegioGuard, REQUIRE_ALGUN_PRIVILEGIO_KEY } from '../auth/guards/algun-privilegio.guard';
import { ModuleGuard } from '../auth/guards/module.guard';
import { PermissionGuard } from '../auth/guards/permission.guard';
import { PagosProveedorController } from './pagos-proveedor.controller';

/**
 * Permisos por handler. Ningún endpoint queda abierto: `PermissionGuard` sin metadata deja pasar.
 */
describe('PagosProveedorController', () => {
  const proto = PagosProveedorController.prototype as any;
  const metodos = Object.getOwnPropertyNames(proto);

  describe('GET config-flujo', () => {
    it('pide CMP_OP_ORDEN_PAGO_VER (guard de clase) y se declara antes de :id', () => {
      expect(Reflect.getMetadata(PATH_METADATA, proto.getConfigFlujo)).toBe('config-flujo');
      expect(Reflect.getMetadata(METHOD_METADATA, proto.getConfigFlujo)).toBe(RequestMethod.GET);
      expect(Reflect.getMetadata(REQUIRE_PERMISSION_KEY, proto.getConfigFlujo)).toEqual({
        modulo: 'COMPRAS',
        privilegio: 'CMP_OP_ORDEN_PAGO_VER',
      });
      expect(Reflect.getMetadata(GUARDS_METADATA, PagosProveedorController)).toContain(PermissionGuard);
      expect(metodos.indexOf('getConfigFlujo')).toBeGreaterThanOrEqual(0);
      expect(metodos.indexOf('getConfigFlujo')).toBeLessThan(metodos.indexOf('findOne'));
    });

    it('pasa empresa y usuario del token al servicio', async () => {
      const flujo = { habilitar_orden_pago: true };
      const getConfigFlujo = jest.fn().mockResolvedValue(flujo);
      const controller = new PagosProveedorController({ getConfigFlujo } as any, {} as any, {} as any, {} as any);
      await expect(controller.getConfigFlujo({ empresa_id: 'emp-1', id: 'u-1' } as any)).resolves.toBe(flujo);
      expect(getConfigFlujo).toHaveBeenCalledWith('emp-1', 'u-1');
    });
  });

  /** Los pipes del parámetro `@Query(nombre)` de un handler (con los enums reales del controller). */
  const pipesDe = (handler: string, nombre: string): PipeTransform[] => {
    const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, PagosProveedorController, handler) as Record<
      string,
      { data?: string; pipes: PipeTransform[] }
    >;
    const arg = Object.values(args).find((a) => a.data === nombre);
    if (!arg) throw new Error(`${handler} no tiene @Query('${nombre}')`);
    return arg.pipes;
  };
  const pasa = async (handler: string, nombre: string, valor: unknown) => {
    let v = valor;
    for (const p of pipesDe(handler, nombre)) v = await p.transform(v, { type: 'query', data: nombre });
    return v;
  };

  describe.each(['findAll', 'getDashboard'])('%s: filtros con ParseEnumPipe (F10)', (handler) => {
    it('estado=aprobada pasa; estado=foo → 400 (y el legacy «pagado» también)', async () => {
      await expect(pasa(handler, 'estado', 'aprobada')).resolves.toBe('aprobada');
      await expect(pasa(handler, 'estado', undefined)).resolves.toBeUndefined();
      for (const clave of ['borrador', 'pendiente_aprobacion', 'rechazada', 'pagada', 'anulada']) {
        await expect(pasa(handler, 'estado', clave)).resolves.toBe(clave);
      }
      await expect(pasa(handler, 'estado', 'foo')).rejects.toBeInstanceOf(BadRequestException);
      await expect(pasa(handler, 'estado', 'pagado')).rejects.toBeInstanceOf(BadRequestException);
    });

    it('origen (manual | compra_auto) y tesoreria (pendiente): otro valor → 400; moneda_id con UUID', async () => {
      await expect(pasa(handler, 'origen', 'manual')).resolves.toBe('manual');
      await expect(pasa(handler, 'origen', 'compra_auto')).resolves.toBe('compra_auto');
      await expect(pasa(handler, 'origen', 'otro')).rejects.toBeInstanceOf(BadRequestException);
      await expect(pasa(handler, 'tesoreria', 'pendiente')).resolves.toBe('pendiente');
      await expect(pasa(handler, 'tesoreria', 'si')).rejects.toBeInstanceOf(BadRequestException);
      await expect(pasa(handler, 'moneda_id', 'no-uuid')).rejects.toBeInstanceOf(BadRequestException);
    });
  });

  describe.each(['findCuentasPagar', 'getCuentasPagarDashboard'])('%s: filtros con ParseEnumPipe (F10)', (handler) => {
    it('estado acepta las claves de la cuota y con_saldo; estado=foo → 400', async () => {
      for (const clave of ['pendiente', 'parcial', 'vencida', 'pagada', 'anulada', 'con_saldo']) {
        await expect(pasa(handler, 'estado', clave)).resolves.toBe(clave);
      }
      await expect(pasa(handler, 'estado', undefined)).resolves.toBeUndefined();
      await expect(pasa(handler, 'estado', 'foo')).rejects.toBeInstanceOf(BadRequestException);
      await expect(pasa(handler, 'estado', 'todos')).rejects.toBeInstanceOf(BadRequestException);
    });

    it('origen_tipo (compra | gasto): otro valor → 400; moneda_id y proveedor_id con UUID', async () => {
      await expect(pasa(handler, 'origen_tipo', 'compra')).resolves.toBe('compra');
      await expect(pasa(handler, 'origen_tipo', 'gasto')).resolves.toBe('gasto');
      await expect(pasa(handler, 'origen_tipo', 'otro')).rejects.toBeInstanceOf(BadRequestException);
      const uuid = '0b8a3c1e-2f4d-4a6b-8c9d-1e2f3a4b5c6d';
      await expect(pasa(handler, 'moneda_id', uuid)).resolves.toBe(uuid);
      await expect(pasa(handler, 'moneda_id', 'no-uuid')).rejects.toBeInstanceOf(BadRequestException);
      await expect(pasa(handler, 'proveedor_id', uuid)).resolves.toBe(uuid);
      await expect(pasa(handler, 'proveedor_id', 'no-uuid')).rejects.toBeInstanceOf(BadRequestException);
    });

    it('pide CMP_CXP_CUENTA_PAGAR_VER', () => {
      expect(Reflect.getMetadata(REQUIRE_PERMISSION_KEY, proto[handler])).toEqual({
        modulo: 'COMPRAS',
        privilegio: 'CMP_CXP_CUENTA_PAGAR_VER',
      });
    });
  });

  it('cuentas-pagar y su dashboard reciben los filtros y el usuario del token (alcance)', async () => {
    const findCuentasPagar = jest.fn().mockResolvedValue({});
    const getCuentasPagarDashboard = jest.fn().mockResolvedValue({});
    const c = new PagosProveedorController(
      { findCuentasPagar, getCuentasPagarDashboard } as any,
      {} as any,
      {} as any,
      {} as any,
    );
    const user = { empresa_id: 'emp-1', id: 'u-1' } as any;
    await c.findCuentasPagar(
      user,
      '2',
      '50',
      'vencimiento',
      '2026-10-01',
      '2026-10-31',
      'prov-1',
      'c-1',
      'gasto',
      'con_saldo',
      'acme',
      'mon-1',
    );
    expect(findCuentasPagar).toHaveBeenCalledWith('emp-1', {
      page: '2',
      limit: '50',
      fecha_tipo: 'vencimiento',
      fecha_desde: '2026-10-01',
      fecha_hasta: '2026-10-31',
      proveedor_id: 'prov-1',
      compra_id: 'c-1',
      origen_tipo: 'gasto',
      estado: 'con_saldo',
      busqueda: 'acme',
      moneda_id: 'mon-1',
      usuarioId: 'u-1',
    });
    await c.getCuentasPagarDashboard(
      user,
      'emision',
      '2026-10-01',
      '2026-10-31',
      'compra',
      'vencida',
      'mon-1',
      'prov-1',
      'c-1',
      'acme',
    );
    expect(getCuentasPagarDashboard).toHaveBeenCalledWith('emp-1', {
      fecha_tipo: 'emision',
      fecha_desde: '2026-10-01',
      fecha_hasta: '2026-10-31',
      origen_tipo: 'compra',
      estado: 'vencida',
      moneda_id: 'mon-1',
      proveedor_id: 'prov-1',
      compra_id: 'c-1',
      busqueda: 'acme',
      usuarioId: 'u-1',
    });
  });

  describe('permisos de los endpoints nuevos (F14) y orden antes de :id', () => {
    const permiso = (handler: string) => Reflect.getMetadata(REQUIRE_PERMISSION_KEY, proto[handler]);

    it.each([
      ['getHistorial', ':id/historial', 'CMP_OP_ORDEN_PAGO_VER'],
      ['proveedoresConSaldo', 'proveedores-con-saldo', 'CMP_OP_ORDEN_PAGO_CREAR'],
    ])('%s (%s) pide %s', (handler, ruta, privilegio) => {
      expect(Reflect.getMetadata(PATH_METADATA, proto[handler])).toBe(ruta);
      expect(Reflect.getMetadata(METHOD_METADATA, proto[handler])).toBe(RequestMethod.GET);
      expect(permiso(handler)).toEqual({ modulo: 'COMPRAS', privilegio });
      expect(metodos.indexOf(handler)).toBeLessThan(metodos.indexOf('findOne'));
    });

    it.each([
      ['cuentasPago', 'cuentas-pago'],
      ['cuentaPago', 'cuenta-pago'],
    ])('%s (%s) pide CREAR o PAGAR de OP con AlgunPrivilegioGuard', (handler, ruta) => {
      expect(Reflect.getMetadata(PATH_METADATA, proto[handler])).toBe(ruta);
      expect(Reflect.getMetadata(REQUIRE_ALGUN_PRIVILEGIO_KEY, proto[handler])).toEqual([
        'CMP_OP_ORDEN_PAGO_CREAR',
        'CMP_OP_ORDEN_PAGO_PAGAR',
      ]);
      expect(Reflect.getMetadata(GUARDS_METADATA, proto[handler])).toContain(AlgunPrivilegioGuard);
      expect(permiso(handler)).toBeUndefined();
      expect(metodos.indexOf(handler)).toBeLessThan(metodos.indexOf('findOne'));
    });

    it('las lecturas de OP siguen con VER', () => {
      for (const h of ['findAll', 'getDashboard', 'findOne', 'getPdf']) {
        expect(permiso(h)).toEqual({ modulo: 'COMPRAS', privilegio: 'CMP_OP_ORDEN_PAGO_VER' });
      }
    });
  });

  describe('cada handler declara su permiso (tabla de la Global, Task 10)', () => {
    const permiso = (handler: string) => Reflect.getMetadata(REQUIRE_PERMISSION_KEY, proto[handler]);
    const OP = (accion: string) => ({ modulo: 'COMPRAS', privilegio: `CMP_OP_ORDEN_PAGO_${accion}` });

    it.each([
      ['create', 'CREAR'],
      ['findAll', 'VER'],
      ['getDashboard', 'VER'],
      ['getConfigFlujo', 'VER'],
      ['getHistorial', 'VER'],
      ['findOne', 'VER'],
      ['getPdf', 'VER'],
      ['enviarAprobacion', 'CREAR'],
      ['aprobar', 'APROBAR'],
      ['rechazar', 'APROBAR'],
      ['ejecutar', 'PAGAR'],
      ['reintentarTesoreria', 'PAGAR'],
      ['reintentarContabilidad', 'PAGAR'],
      ['anular', 'ANULAR'],
      ['getCuentasPendientes', 'CREAR'],
      ['proveedoresConSaldo', 'CREAR'],
    ])('%s pide CMP_OP_ORDEN_PAGO_%s', (handler, accion) => {
      expect(permiso(handler)).toEqual(OP(accion));
      expect(Reflect.getMetadata(REQUIRE_ALGUN_PRIVILEGIO_KEY, proto[handler])).toBeUndefined();
    });

    it.each(['cuentasPago', 'cuentaPago'])('%s pide CREAR o PAGAR de OP, sin RequirePermission', (handler) => {
      expect(permiso(handler)).toBeUndefined();
      expect(Reflect.getMetadata(REQUIRE_ALGUN_PRIVILEGIO_KEY, proto[handler])).toEqual([
        'CMP_OP_ORDEN_PAGO_CREAR',
        'CMP_OP_ORDEN_PAGO_PAGAR',
      ]);
      expect(Reflect.getMetadata(GUARDS_METADATA, proto[handler])).toEqual([AlgunPrivilegioGuard]);
    });

    it('ningún handler HTTP queda sin permiso declarado', () => {
      const handlers = metodos.filter(
        (m) => m !== 'constructor' && Reflect.getMetadata(PATH_METADATA, proto[m]) !== undefined,
      );
      expect(handlers.length).toBeGreaterThan(20);
      const abiertos = handlers.filter(
        (h) => !permiso(h) && !Reflect.getMetadata(REQUIRE_ALGUN_PRIVILEGIO_KEY, proto[h]),
      );
      expect(abiertos).toEqual([]);
    });
  });

  describe('cada lectura recibe el usuario del token (alcance por sucursal)', () => {
    const user = { empresa_id: 'emp-1', id: 'u-1' } as any;
    const servicio = () => ({
      findAll: jest.fn().mockResolvedValue({}),
      getDashboard: jest.fn().mockResolvedValue({}),
      findOne: jest.fn().mockResolvedValue({}),
      getHistorial: jest.fn().mockResolvedValue({}),
      getCuentasPendientes: jest.fn().mockResolvedValue({}),
      proveedoresConSaldo: jest.fn().mockResolvedValue([]),
      cuentasPago: jest.fn().mockResolvedValue([]),
      cuentaPago: jest.fn().mockResolvedValue({}),
      generatePdf: jest.fn().mockResolvedValue({ filename: 'x.pdf', pdfBuffer: Buffer.from('') }),
    });

    it('findAll, dashboard, detalle, historial, PDF, cuentas pendientes y proveedores con saldo', async () => {
      const s = servicio();
      const c = new PagosProveedorController(s as any, {} as any, {} as any, {} as any);
      await c.findAll(
        user,
        '2',
        '50',
        '2026-10-01',
        '2026-10-05',
        'prov-1',
        undefined,
        'manual',
        undefined,
        'aprobada',
        'acme',
        'mon-1',
        'pendiente',
      );
      expect(s.findAll).toHaveBeenCalledWith('emp-1', {
        page: '2',
        limit: '50',
        fecha_desde: '2026-10-01',
        fecha_hasta: '2026-10-05',
        proveedor_id: 'prov-1',
        compra_id: undefined,
        origen: 'manual',
        origen_tipo: undefined,
        estado: 'aprobada',
        busqueda: 'acme',
        moneda_id: 'mon-1',
        tesoreria: 'pendiente',
        usuarioId: 'u-1',
      });
      await c.getDashboard(
        user,
        '2026-10-01',
        undefined,
        undefined,
        undefined,
        'pagada',
        undefined,
        undefined,
        undefined,
        undefined,
      );
      expect(s.getDashboard).toHaveBeenCalledWith(
        'emp-1',
        expect.objectContaining({ estado: 'pagada', usuarioId: 'u-1' }),
      );
      await c.findOne('op-1', user);
      expect(s.findOne).toHaveBeenCalledWith('op-1', 'emp-1', undefined, 'u-1');
      await c.getHistorial('op-1', user);
      expect(s.getHistorial).toHaveBeenCalledWith('op-1', 'emp-1', 'u-1');
      const res = { set: jest.fn(), send: jest.fn() };
      await c.getPdf('op-1', user, res);
      expect(s.generatePdf).toHaveBeenCalledWith('op-1', 'emp-1', 'u-1');
      await c.getCuentasPendientes(user, 'prov-1');
      expect(s.getCuentasPendientes).toHaveBeenCalledWith('emp-1', 'prov-1', 'u-1');
      await c.proveedoresConSaldo(user, 'acme');
      expect(s.proveedoresConSaldo).toHaveBeenCalledWith('emp-1', 'u-1', 'acme');
      await c.cuentasPago(user, { moneda_id: 'mon-1' } as any);
      expect(s.cuentasPago).toHaveBeenCalledWith('emp-1', 'mon-1');
      await c.cuentaPago(user, { medio_pago_id: 'mp-1', moneda_id: 'mon-1', cotizacion: 7300 } as any);
      expect(s.cuentaPago).toHaveBeenCalledWith('emp-1', {
        medio_pago_id: 'mp-1',
        moneda_id: 'mon-1',
        cotizacion: 7300,
      });
    });
  });

  describe('config de Compras (D4): la pantalla de Opciones pide los privilegios de Administración', () => {
    const permiso = (handler: string) => Reflect.getMetadata(REQUIRE_PERMISSION_KEY, proto[handler]);

    it.each([
      ['getConfig', RequestMethod.GET, 'ADM_CCFG_CONFIG_VER'],
      ['updateConfig', RequestMethod.PUT, 'ADM_CCFG_CONFIG_EDITAR'],
    ])('%s pide ADMINISTRACION · %s (el ModuleGuard de COMPRAS de la clase queda)', (handler, verbo, privilegio) => {
      expect(Reflect.getMetadata(PATH_METADATA, proto[handler])).toBe('config');
      expect(Reflect.getMetadata(METHOD_METADATA, proto[handler])).toBe(verbo);
      expect(permiso(handler)).toEqual({ modulo: 'ADMINISTRACION', privilegio });
      expect(Reflect.getMetadata(GUARDS_METADATA, PagosProveedorController)).toContain(ModuleGuard);
    });

    it('el GET lee la config de la pantalla y el PUT pasa el usuario para la auditoría', async () => {
      const leerConfigComprasPantalla = jest.fn().mockResolvedValue({ niveles_activos: { compra: 0, gasto: 0 } });
      const updateConfigCompras = jest.fn().mockResolvedValue({ ok: true });
      const controller = new PagosProveedorController({ leerConfigComprasPantalla, updateConfigCompras } as any, {} as any, {} as any, {} as any);
      const user = { empresa_id: 'emp-1', id: 'u-1' } as any;
      await controller.getConfig(user);
      await controller.updateConfig(user, { permitir_pago_parcial: true });
      expect(leerConfigComprasPantalla).toHaveBeenCalledWith('emp-1');
      expect(updateConfigCompras).toHaveBeenCalledWith('emp-1', { permitir_pago_parcial: true }, 'u-1');
    });
  });

  describe('plan de pagos y extracto: permisos y consulta (D5e)', () => {
    const permiso = (handler: string) => Reflect.getMetadata(REQUIRE_PERMISSION_KEY, proto[handler]);
    const uuid1 = '0b8a3c1e-2f4d-4a6b-8c9d-1e2f3a4b5c6d';
    const uuid2 = '5f1d2c3b-4a59-4b68-9a7c-8d9e0f1a2b3c';
    const rechazo = async (handler: string, nombre: string, valor: unknown) => {
      const e = await pasa(handler, nombre, valor).then(
        () => null,
        (x: unknown) => x,
      );
      return { e, cuerpo: (e as { getResponse?: () => unknown } | null)?.getResponse?.() };
    };

    it.each([
      ['planPagosProgramado', 'CMP_PP_PLAN_PAGOS_VER'],
      ['reportePlanPagosProgramado', 'CMP_PP_PLAN_PAGOS_EXPORTAR'],
      ['programarPagos', 'CMP_PP_PLAN_PAGOS_PROGRAMAR'],
      ['extracto', 'CMP_CXP_CUENTA_PAGAR_VER'],
      ['extractoExcel', 'CMP_CXP_CUENTA_PAGAR_VER'],
      ['extractoPdf', 'CMP_CXP_CUENTA_PAGAR_VER'],
    ])('%s pide %s', (handler, privilegio) => {
      expect(permiso(handler)).toEqual({ modulo: 'COMPRAS', privilegio });
    });

    describe.each(['planPagosProgramado', 'reportePlanPagosProgramado'])('%s: periodos y proveedor_ids', (handler) => {
      it('periodos: 6 → 6, sin valor → undefined; 0, 25 y abc → 400 FILTRO_INVALIDO', async () => {
        await expect(pasa(handler, 'periodos', '6')).resolves.toBe(6);
        await expect(pasa(handler, 'periodos', '24')).resolves.toBe(24);
        await expect(pasa(handler, 'periodos', undefined)).resolves.toBeUndefined();
        for (const malo of ['0', '25', 'abc']) {
          const { e, cuerpo } = await rechazo(handler, 'periodos', malo);
          expect(e).toBeInstanceOf(BadRequestException);
          expect(cuerpo).toMatchObject({ codigo: 'FILTRO_INVALIDO', campo: 'periodos' });
        }
      });

      it('proveedor_ids: dos UUID → arreglo de 2; otro valor → 400 FILTRO_INVALIDO', async () => {
        await expect(pasa(handler, 'proveedor_ids', `${uuid1},${uuid2}`)).resolves.toEqual([uuid1, uuid2]);
        await expect(pasa(handler, 'proveedor_ids', undefined)).resolves.toBeUndefined();
        expect((await rechazo(handler, 'proveedor_ids', 'x')).cuerpo).toMatchObject({ codigo: 'FILTRO_INVALIDO', campo: 'proveedor_ids' });
      });
    });

    describe.each(['extracto', 'extractoExcel', 'extractoPdf'])('%s: desde, hasta y proveedor', (handler) => {
      it('desde y hasta: fecha real o 400 FILTRO_INVALIDO con su campo', async () => {
        await expect(pasa(handler, 'desde', '2026-02-28')).resolves.toBe('2026-02-28');
        await expect(pasa(handler, 'hasta', undefined)).resolves.toBeUndefined();
        for (const malo of ['2026-02-30', '05/10/2026']) {
          expect((await rechazo(handler, 'desde', malo)).cuerpo).toMatchObject({ codigo: 'FILTRO_INVALIDO', campo: 'desde' });
        }
        expect((await rechazo(handler, 'hasta', '2026-13-01')).cuerpo).toMatchObject({ codigo: 'FILTRO_INVALIDO', campo: 'hasta' });
      });

      it('proveedorId que no es UUID → 404 PROVEEDOR_NO_ENCONTRADO', async () => {
        await expect(pasa(handler, 'proveedorId', uuid1)).resolves.toBe(uuid1);
        const { e, cuerpo } = await rechazo(handler, 'proveedorId', 'x');
        expect(e).toBeInstanceOf(NotFoundException);
        expect(cuerpo).toMatchObject({ codigo: 'PROVEEDOR_NO_ENCONTRADO' });
      });
    });

    it('extractoPdf: moneda en mayúsculas de tres letras; usd → 400 FILTRO_INVALIDO', async () => {
      await expect(pasa('extractoPdf', 'moneda', 'USD')).resolves.toBe('USD');
      await expect(pasa('extractoPdf', 'moneda', undefined)).resolves.toBeUndefined();
      expect((await rechazo('extractoPdf', 'moneda', 'usd')).cuerpo).toMatchObject({ codigo: 'FILTRO_INVALIDO', campo: 'moneda' });
    });
  });
});
