import { BadRequestException, ForbiddenException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ClsService } from 'nestjs-cls';
import { RoleEntity } from '../../entities/role.entity';
import { AccessLevel, RolePermissionEntity } from '../../entities/role-permission.entity';
import {
  CLS_ROLE_VIEW_ALL_BOOKINGS_QUERIES,
  CLS_TENANT_ID,
  CLS_USER_PERMISSIONS,
} from '../../common/cls/cls.constants';

const LEVEL: Record<string, number> = {
  [AccessLevel.NONE]: 0,
  [AccessLevel.VIEW]: 1,
  [AccessLevel.CREATE]: 2,
  [AccessLevel.EDIT]: 3,
  [AccessLevel.DELETE]: 4,
};

export interface RoleRights {
  permissions: Array<{ module: string; access_level: string }>;
  view_all_bookings_queries?: boolean;
}

/**
 * C12 (client 2026-10-19) — no privilege escalation. A user may only
 * manage users / roles whose rights are the same as or below their
 * own, and may only grant rights they hold. Admin holds every right,
 * so only Admin can create, edit, reset or remove an Admin. Driven by
 * the permission matrix — never by role names (governance rule).
 */
@Injectable()
export class RolePrivilegeService {
  constructor(
    @InjectRepository(RoleEntity)
    private readonly roleRepo: Repository<RoleEntity>,
    @InjectRepository(RolePermissionEntity)
    private readonly rolePermRepo: Repository<RolePermissionEntity>,
    private readonly cls: ClsService,
  ) {}

  /** Refuse when `rights` go beyond the acting user's own. */
  assertWithinOwnRights(rights: RoleRights, message: string): void {
    const own = this.cls.get<Record<string, string> | null>(CLS_USER_PERMISSIONS) ?? {};
    const exceeds = rights.permissions.some(
      (p) => (LEVEL[p.access_level] ?? 0) > (LEVEL[own[p.module]] ?? 0),
    );
    const ownViewAll = this.cls.get<boolean>(CLS_ROLE_VIEW_ALL_BOOKINGS_QUERIES) === true;
    if (exceeds || (rights.view_all_bookings_queries === true && !ownViewAll)) {
      throw new ForbiddenException(message);
    }
  }

  /** Refuse to touch a role (or its users) stronger than the actor's. */
  async assertCanManageRole(roleId: string, action: string): Promise<RoleEntity> {
    const tenantId = this.cls.get<string>(CLS_TENANT_ID);
    const role = await this.roleRepo.findOne({
      where: { id: roleId, tenant_id: tenantId, is_deleted: false } as never,
    });
    if (!role) throw new BadRequestException('Invalid role ID');
    const permissions = await this.rolePermRepo.find({
      where: { role: { id: roleId }, tenant_id: tenantId, is_deleted: false } as never,
      select: { module: true, access_level: true },
    });
    this.assertWithinOwnRights(
      { permissions, view_all_bookings_queries: role.view_all_bookings_queries },
      `You can't ${action} — the "${role.name}" role has more rights than yours.`,
    );
    return role;
  }
}
