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

/** Shared helper: decode JWT payload without signature verification (Kong already verified). */
export function decodeJwtRoles(authHeader: string | undefined): string[] {
  if (!authHeader?.startsWith('Bearer ')) return [];
  const parts = authHeader.slice(7).split('.');
  if (parts.length !== 3) return [];
  try {
    const payload = JSON.parse(
      Buffer.from(parts[1], 'base64url').toString('utf-8'),
    ) as { roles?: string[] };
    return Array.isArray(payload.roles) ? payload.roles : [];
  } catch {
    return [];
  }
}

const PLATFORM_ROLES = ['platform_admin', 'platform_super_admin'];

/**
 * Accepts requests from `platform_admin` OR `platform_super_admin`.
 * Signature verification skipped — Kong validates the JWT upstream.
 */
@Injectable()
export class PlatformAdminGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<{ headers: Record<string, string> }>();
    const roles = decodeJwtRoles(request.headers['authorization']);

    if (!request.headers['authorization']?.startsWith('Bearer ')) {
      throw new UnauthorizedException('Missing authorization token');
    }
    if (roles.length === 0) {
      throw new UnauthorizedException('Invalid token payload');
    }
    if (!roles.some((r) => PLATFORM_ROLES.includes(r))) {
      throw new ForbiddenException('Platform admin access required');
    }
    return true;
  }
}
