import {
  Injectable,
  CanActivate,
  ExecutionContext,
  UnauthorizedException,
  ForbiddenException,
} from '@nestjs/common';

/**
 * AdminGuard - Restricts access to admin-only endpoints
 *
 * Validates that:
 * 1. Request has a valid authenticated user
 * 2. User has admin role
 *
 * Used to protect security IP log endpoints from unauthorized access.
 */
@Injectable()
export class AdminGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const user = request.user;

    // Check authentication
    if (!user || !user.id) {
      throw new UnauthorizedException('Authentication required');
    }

    // Check admin role
    // Supports both 'role' and 'roles' array patterns
    const isAdmin = this.checkAdminRole(user);

    if (!isAdmin) {
      throw new ForbiddenException('Admin access required');
    }

    return true;
  }

  private checkAdminRole(user: {
    role?: string;
    roles?: string[];
    isAdmin?: boolean;
  }): boolean {
    // Direct admin flag
    if (user.isAdmin === true) {
      return true;
    }

    // Single role check
    if (user.role === 'admin' || user.role === 'ADMIN') {
      return true;
    }

    // Roles array check
    if (Array.isArray(user.roles)) {
      return user.roles.some(
        (role) => role.toLowerCase() === 'admin' || role.toLowerCase() === 'super_admin',
      );
    }

    return false;
  }
}
