import { GUARDS_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
import { RequestMethod } from '@nestjs/common';
import { REQUIRE_MODULE_KEY } from 'src/auth/decorators/require-module.decorator';
import { REQUIRE_PERMISSION_KEY } from 'src/auth/decorators/require-permission.decorator';
import { ModuleGuard } from 'src/auth/guards/module.guard';
import { PermissionGuard } from 'src/auth/guards/permission.guard';
import { NumeracionesController } from './numeraciones.controller';

/**
 * Guardas de `/numeraciones` (carril C, T1).
 * - `PATCH :id/correlativo` (ajuste del correlativo fiscal, solo hacia adelante) pide ADM_NUM_NUMERACION_EDITAR con el
 *   módulo ADMINISTRACION, como el resto de la edición.
 * - Las demás rutas quedan fijadas tal cual estaban (JWT + ModuleGuard + PermissionGuard a nivel de clase).
 */
type Ctl = { prototype: object; name: string };
const handler = (c: Ctl, m: string) => {
  const h = Object.getOwnPropertyDescriptor(c.prototype, m)?.value as object | undefined;
  if (!h) throw new Error(`${c.name}.${m} no existe`);
  return h;
};
const C = NumeracionesController;
const guardsDe = (m: string) => [...(Reflect.getMetadata(GUARDS_METADATA, C) ?? []), ...(Reflect.getMetadata(GUARDS_METADATA, handler(C, m)) ?? [])];
const permisoDe = (m: string) => Reflect.getMetadata(REQUIRE_PERMISSION_KEY, handler(C, m));
const moduloDe = (m: string) => Reflect.getMetadata(REQUIRE_MODULE_KEY, handler(C, m)) ?? Reflect.getMetadata(REQUIRE_MODULE_KEY, C);

/** método → privilegio */
const RUTAS: Record<string, string> = {
  create: 'ADM_NUM_NUMERACION_CREAR',
  findAllByPuntoExpedicion: 'ADM_NUM_NUMERACION_VER',
  findAllBySucursal: 'ADM_NUM_NUMERACION_VER',
  findOne: 'ADM_NUM_NUMERACION_VER',
  getNextNumber: 'ADM_NUM_NUMERACION_VER',
  reserveNextNumber: 'ADM_NUM_NUMERACION_EDITAR',
  update: 'ADM_NUM_NUMERACION_EDITAR',
  ajustarCorrelativo: 'ADM_NUM_NUMERACION_EDITAR',
  incrementNumber: 'ADM_NUM_NUMERACION_EDITAR',
  setDefault: 'ADM_NUM_NUMERACION_EDITAR',
  unsetDefault: 'ADM_NUM_NUMERACION_EDITAR',
  toggleStatus: 'ADM_NUM_NUMERACION_EDITAR',
  remove: 'ADM_NUM_NUMERACION_ELIMINAR',
};

describe('Guardas de /numeraciones', () => {
  it.each(Object.entries(RUTAS))('%s pide %s con el módulo ADMINISTRACION', (m, priv) => {
    expect(permisoDe(m)).toEqual({ modulo: 'ADMINISTRACION', privilegio: priv });
    expect(moduloDe(m)).toBe('ADMINISTRACION');
    expect(guardsDe(m)).toEqual(expect.arrayContaining([ModuleGuard, PermissionGuard]));
    expect(guardsDe(m)).toHaveLength(3); // JWT + módulo + permiso
  });

  it('el mapa cubre todas las rutas del controller', () => {
    const rutas = Object.getOwnPropertyNames(C.prototype).filter((m) => m !== 'constructor');
    expect(rutas.sort()).toEqual(Object.keys(RUTAS).sort());
  });

  it('el ajuste es PATCH :id/correlativo', () => {
    expect(Reflect.getMetadata(METHOD_METADATA, handler(C, 'ajustarCorrelativo'))).toBe(RequestMethod.PATCH);
    expect(Reflect.getMetadata(PATH_METADATA, handler(C, 'ajustarCorrelativo'))).toBe(':id/correlativo');
  });

  it('PUT :id, DELETE :id y el ajuste pasan la empresa del token al servicio', async () => {
    const service = {
      ajustarCorrelativo: jest.fn().mockResolvedValue({}),
      update: jest.fn().mockResolvedValue({}),
      remove: jest.fn().mockResolvedValue({}),
    };
    const controller = new NumeracionesController(service as any);
    const user = { id: 'u1', empresa_id: 'e1' } as any;
    const dto = { numero_actual: 20, motivo: 'Salto por talonario perdido' };

    await controller.ajustarCorrelativo('n1', dto, user);
    await controller.update('n1', { numero_final: 50 }, user);
    await controller.remove('n1', user);

    expect(service.ajustarCorrelativo).toHaveBeenCalledWith('n1', dto, 'e1', 'u1');
    expect(service.update).toHaveBeenCalledWith('n1', { numero_final: 50 }, 'e1', 'u1');
    expect(service.remove).toHaveBeenCalledWith('n1', 'e1', 'u1');
  });
});
