import { BadRequestException, ForbiddenException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ClsService } from 'nestjs-cls';
import { RolePrivilegeService } from './role-privilege.service';
import { RoleEntity } from '../../entities/role.entity';
import { RolePermissionEntity } from '../../entities/role-permission.entity';
import {
  CLS_ROLE_VIEW_ALL_BOOKINGS_QUERIES,
  CLS_TENANT_ID,
  CLS_USER_PERMISSIONS,
} from '../../common/cls/cls.constants';

describe('RolePrivilegeService', () => {
  let service: RolePrivilegeService;
  const roleRepo = { findOne: jest.fn() };
  const rolePermRepo = { find: jest.fn() };
  let ctx: Record<string, unknown>;
  const cls = { get: jest.fn((k: string) => ctx[k]) };

  beforeEach(async () => {
    ctx = {
      [CLS_TENANT_ID]: 't1',
      [CLS_USER_PERMISSIONS]: { settings: 'create', booking: 'view' },
      [CLS_ROLE_VIEW_ALL_BOOKINGS_QUERIES]: false,
    };
    const module = await Test.createTestingModule({
      providers: [
        RolePrivilegeService,
        { provide: getRepositoryToken(RoleEntity), useValue: roleRepo },
        { provide: getRepositoryToken(RolePermissionEntity), useValue: rolePermRepo },
        { provide: ClsService, useValue: cls },
      ],
    }).compile();
    service = module.get(RolePrivilegeService);
  });

  afterEach(() => jest.clearAllMocks());

  describe('assertCanManageRole', () => {
    it('refuses a role with more rights (Sales with settings:create vs Admin)', async () => {
      roleRepo.findOne.mockResolvedValue({ id: 'admin', name: 'Admin' });
      rolePermRepo.find.mockResolvedValue([{ module: 'settings', access_level: 'delete' }]);
      await expect(service.assertCanManageRole('admin', 'edit this user')).rejects.toThrow(
        ForbiddenException,
      );
    });

    it('allows a role at or below the acting user', async () => {
      roleRepo.findOne.mockResolvedValue({ id: 'r', name: 'Sales Team' });
      rolePermRepo.find.mockResolvedValue([
        { module: 'settings', access_level: 'view' },
        { module: 'booking', access_level: 'view' },
      ]);
      await expect(service.assertCanManageRole('r', 'edit this user')).resolves.toMatchObject({
        id: 'r',
      });
    });

    it('refuses a role that sees all bookings when the actor does not', async () => {
      roleRepo.findOne.mockResolvedValue({ id: 'r', name: 'Ops', view_all_bookings_queries: true });
      rolePermRepo.find.mockResolvedValue([]);
      await expect(service.assertCanManageRole('r', 'edit this role')).rejects.toThrow(
        ForbiddenException,
      );
    });

    it('only looks up roles in the current tenant', async () => {
      roleRepo.findOne.mockResolvedValue(null);
      await expect(service.assertCanManageRole('other-tenant-role', 'x')).rejects.toThrow(
        BadRequestException,
      );
      expect(roleRepo.findOne).toHaveBeenCalledWith({
        where: expect.objectContaining({ id: 'other-tenant-role', tenant_id: 't1' }),
      });
    });
  });

  describe('assertWithinOwnRights', () => {
    it('refuses a module the actor does not hold', () => {
      expect(() =>
        service.assertWithinOwnRights(
          { permissions: [{ module: 'accounting', access_level: 'view' }] },
          'no',
        ),
      ).toThrow(ForbiddenException);
    });
  });
});
