import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

/**
 * Roles Guard for Role-Based Access Control (RBAC)
 *
 * This guard:
 * - Checks if the authenticated user has the required role(s)
 * - Works in conjunction with JwtAuthGuard
 * - Uses @Roles() decorator to specify required roles
 *
 * Usage:
 * @UseGuards(JwtAuthGuard, RolesGuard)
 * @Roles('admin', 'manager')
 * @Get('admin-only')
 * adminRoute(@CurrentUser() user: UserPayload) {
 *   return { message: 'Admin access granted' };
 * }
 */
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    // Get required roles from @Roles() decorator
    const requiredRoles = this.reflector.getAllAndOverride<string[]>('roles', [
      context.getHandler(),
      context.getClass(),
    ]);

    // If no roles are required, allow access
    if (!requiredRoles || requiredRoles.length === 0) {
      return true;
    }

    // Get user from request (should be set by JwtAuthGuard)
    const { user } = context.switchToHttp().getRequest();

    // Check if user has any of the required roles
    if (!user || !user.role) {
      return false;
    }

    // Case-insensitive role comparison
    const userRole = user.role.toLowerCase();
    const requiredRolesLower = requiredRoles.map(r => r.toLowerCase());

    return requiredRolesLower.includes(userRole);
  }
}
