import {
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { decodeJwtRoles } from './platform-admin.guard';

/**
 * Requires the caller to have the `platform_super_admin` role.
 * Used for destructive operations (delete version, etc.).
 * Intended to be stacked on top of PlatformAdminGuard:
 *   class: @UseGuards(PlatformAdminGuard)   → admits platform_admin + platform_super_admin
 *   method: @UseGuards(PlatformSuperAdminGuard) → further restricts to platform_super_admin only
 */
@Injectable()
export class PlatformSuperAdminGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<{ headers: Record<string, string> }>();
    const authHeader = request.headers['authorization'];

    if (!authHeader?.startsWith('Bearer ')) {
      throw new UnauthorizedException('Missing authorization token');
    }

    const roles = decodeJwtRoles(authHeader);
    if (roles.length === 0) {
      throw new UnauthorizedException('Invalid token payload');
    }
    if (!roles.includes('platform_super_admin')) {
      throw new ForbiddenException('Platform super admin access required for this operation');
    }
    return true;
  }
}
