import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtAuthGuard } from '../../modules/auth/guards/jwt-auth.guard';
import { Reflector } from '@nestjs/core';

/**
 * AdminGuard - Protects admin-only endpoints
 *
 * Usage:
 * @Controller('api/v1/admin')
 * @UseGuards(AdminGuard)
 * export class AdminController { ... }
 *
 * Or on specific routes:
 * @Get('users')
 * @UseGuards(AdminGuard)
 * getUsers() { ... }
 */
@Injectable()
export class AdminGuard extends JwtAuthGuard implements CanActivate {
  constructor(reflector: Reflector) {
    super(reflector);
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    // First check JWT authentication
    const isAuthenticated = await super.canActivate(context);

    if (!isAuthenticated) {
      throw new UnauthorizedException('Authentication required');
    }

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

    if (!user) {
      throw new UnauthorizedException('User not found in request');
    }

    // Check if user has admin privileges
    if (!user.isAdmin || user.globalRole !== 'admin') {
      throw new ForbiddenException(
        'Admin access required. This action requires administrator privileges.',
      );
    }

    return true;
  }
}
