import { ForbiddenException, type ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AccessLevel } from '../../entities/role-permission.entity';
import { PermissionGuard, type PermissionRequirement } from './permission.guard';

type Perm = { module: string; access_level: AccessLevel };

function setup(perms: Perm[], requirement: PermissionRequirement | undefined) {
  const reflector = {
    getAllAndOverride: jest.fn().mockReturnValue(requirement),
  } as unknown as Reflector;
  const redis = { get: jest.fn().mockResolvedValue(null), set: jest.fn() };
  const repo = { find: jest.fn().mockResolvedValue(perms) };
  const cls = { get: jest.fn().mockReturnValue('tenant-1') };
  const guard = new PermissionGuard(reflector, redis as never, repo as never, cls as never);
  const ctx = {
    getHandler: () => null,
    getClass: () => null,
    switchToHttp: () => ({ getRequest: () => ({ user: { role: { id: 'role-1' } } }) }),
  } as unknown as ExecutionContext;
  return { guard, ctx };
}

describe('PermissionGuard', () => {
  it('passes when the main module meets the level', async () => {
    const { guard, ctx } = setup([{ module: 'collect_payment', access_level: AccessLevel.EDIT }], {
      module: 'collect_payment',
      accessLevel: AccessLevel.EDIT,
    });
    await expect(guard.canActivate(ctx)).resolves.toBe(true);
  });

  it('refuses when the main module is below the level (no anyOf)', async () => {
    const { guard, ctx } = setup(
      [
        { module: 'collect_payment', access_level: AccessLevel.VIEW },
        { module: 'payment_settlement', access_level: AccessLevel.DELETE },
      ],
      { module: 'collect_payment', accessLevel: AccessLevel.EDIT },
    );
    await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(ForbiddenException);
  });

  it('passes through an anyOf module for shared read-only lookups', async () => {
    const { guard, ctx } = setup(
      [
        { module: 'collect_payment', access_level: AccessLevel.NONE },
        { module: 'payment_settlement', access_level: AccessLevel.VIEW },
      ],
      { module: 'collect_payment', accessLevel: AccessLevel.VIEW, anyOf: ['payment_settlement'] },
    );
    await expect(guard.canActivate(ctx)).resolves.toBe(true);
  });

  it('refuses when neither the module nor any anyOf module is enough', async () => {
    const { guard, ctx } = setup(
      [
        { module: 'pay_supplier', access_level: AccessLevel.NONE },
        { module: 'payment_settlement', access_level: AccessLevel.NONE },
      ],
      { module: 'pay_supplier', accessLevel: AccessLevel.VIEW, anyOf: ['payment_settlement'] },
    );
    await expect(guard.canActivate(ctx)).rejects.toBeInstanceOf(ForbiddenException);
  });

  it('allows routes with no requirement', async () => {
    const { guard, ctx } = setup([], undefined);
    await expect(guard.canActivate(ctx)).resolves.toBe(true);
  });
});
