import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ROLES_KEY } from './roles.decorator';
import { UserService } from '../user/user.service';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private userService: UserService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredRoles = this.reflector.getAllAndOverride<string[]>(
      ROLES_KEY,
      [context.getHandler(), context.getClass()],
    );

    if (!requiredRoles) {
      return true;
    }

    const request = context.switchToHttp().getRequest();
    const user = request.user;
    const activeRole = user.activeRole;
    // check if the activeRole is in the requiredRoles
    const hasRole = requiredRoles.some((role) => activeRole === role);
    if (!hasRole) {
      throw new ForbiddenException(
        `Access denied. User roles (${activeRole}) are not in required roles: [${requiredRoles.join(', ')}]`,
      );
    }

    return true;
  }
}
