import { Injectable, CanActivate, ExecutionContext, ForbiddenException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { UserRole } from '../enums';
import { ERROR_CODES } from '../constants';

export const ROLES_KEY = 'roles';

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

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

    if (!requiredRoles) {
      return true;
    }

    const request = context.switchToHttp().getRequest();
    const user = request.user;

    if (!user || !user.role) {
      throw new ForbiddenException({
        code: ERROR_CODES.INSUFFICIENT_PERMISSIONS,
        message: 'Access denied',
      });
    }

    // Map CITIZEN role to APPLICANT for backwards compatibility
    const normalizedUserRole = user.role === 'CITIZEN' ? UserRole.APPLICANT : user.role;
    const hasRole = requiredRoles.some(role => normalizedUserRole === role);

    if (!hasRole) {
      throw new ForbiddenException({
        code: ERROR_CODES.INSUFFICIENT_PERMISSIONS,
        message: 'You do not have permission to perform this action',
      });
    }

    return true;
  }
}
