import { ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { RolesGuard } from './roles.guard';

describe('RolesGuard', () => {
  let guard: RolesGuard;

  beforeEach(() => {
    guard = new RolesGuard(new Reflector());
  });

  const context = (user: unknown, roles?: string[]) =>
    ({
      switchToHttp: () => ({ getRequest: () => ({ user }) }),
      getHandler: () => (roles ? { __roles: roles } : {}),
      getClass: () => ({}),
    }) as never;

  it('passes public routes (no authenticated user)', () => {
    expect(guard.canActivate(context(undefined))).toBe(true);
  });

  it('passes ADMIN users by default', () => {
    expect(guard.canActivate(context({ id: 1n, username: 'a', role: 'ADMIN' }))).toBe(true);
  });

  it('blocks users without the ADMIN role', () => {
    expect(() => guard.canActivate(context({ id: 1n, username: 'a', role: 'VIEWER' }))).toThrow(
      ForbiddenException,
    );
  });
});
