import { ForbiddenException, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../auth/roles.guard';
import { InventoryController } from './inventory.controller';
import { getRolesMetadata, mockHttpContext } from '../test-utils/security-test-helpers';

describe('Inventory admin security', () => {
  const adminHandlers: Array<[string, Function]> = [
    ['findAllAdmin', InventoryController.prototype.findAllAdmin],
    ['createAdmin', InventoryController.prototype.createAdmin],
    ['updateAdmin', InventoryController.prototype.updateAdmin],
    ['removeAdmin', InventoryController.prototype.removeAdmin],
    ['mergeAdmin', InventoryController.prototype.mergeAdmin],
    ['previewMergeAdmin', InventoryController.prototype.previewMergeAdmin],
  ];

  it('alla admin-endpoints har @Roles("admin") metadata', () => {
    for (const [, handler] of adminHandlers) {
      expect(getRolesMetadata(handler)).toEqual(['admin']);
    }
  });

  it.each(adminHandlers)('RolesGuard nekar icke-admin (403) på %s', (_name, handler) => {
    const reflector = new Reflector();
    const guard = new RolesGuard(reflector);
    const context = mockHttpContext({
      handler,
      clazz: InventoryController,
      user: { role: 'user' },
    });

    expect(() => guard.canActivate(context)).toThrow(ForbiddenException);
  });

  it.each(adminHandlers)('RolesGuard tillåter admin (200/allow) på %s', (_name, handler) => {
    const reflector = new Reflector();
    const guard = new RolesGuard(reflector);
    const context = mockHttpContext({
      handler,
      clazz: InventoryController,
      user: { role: 'admin' },
    });

    expect(guard.canActivate(context)).toBe(true);
  });

  it('JwtAuthGuard mappar saknad användare till 401', () => {
    const guard = new JwtAuthGuard(new Reflector());

    expect(() => guard.handleRequest(null, null, null)).toThrow(UnauthorizedException);
  });

  it('JwtAuthGuard släpper igenom autentiserad användare (200/allow)', () => {
    const guard = new JwtAuthGuard(new Reflector());
    const user = { userId: 42, role: 'admin' };

    expect(guard.handleRequest(null, user, null)).toBe(user);
  });

  it('JwtAuthGuard-logg innehåller userId men inte token', () => {
    const guard = new JwtAuthGuard(new Reflector());
    const logSpy = jest.fn();
    (guard as any).logger = { log: logSpy };
    const user = {
      userId: 77,
      role: 'admin',
      accessToken: 'secret-token-should-not-appear',
    };

    guard.handleRequest(null, user, null);

    expect(logSpy).toHaveBeenCalledTimes(1);
    const loggedMessage = String(logSpy.mock.calls[0][0] ?? '');
    expect(loggedMessage).toContain('77');
    expect(loggedMessage).not.toContain('secret-token-should-not-appear');
  });
});
