import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import type { Request } from "express";
import { AgentConfigService, type ContainerTokenValidation } from "./agent-config.service";

export interface AgentConfigRequest extends Request {
  containerAuth?: ContainerTokenValidation;
}

@Injectable()
export class AgentConfigGuard implements CanActivate {
  constructor(private readonly agentConfigService: AgentConfigService) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest<AgentConfigRequest>();
    const token = this.extractBearerToken(request.headers.authorization);

    if (!token) {
      throw new UnauthorizedException("Missing Bearer token");
    }

    const containerAuth = await this.agentConfigService.validateContainerToken(token);
    if (!containerAuth) {
      throw new UnauthorizedException("Invalid container token");
    }

    request.containerAuth = containerAuth;
    return true;
  }

  private extractBearerToken(headerValue: string | string[] | undefined): string | null {
    const normalizedHeader = Array.isArray(headerValue) ? headerValue[0] : headerValue;
    if (!normalizedHeader) {
      return null;
    }

    const [scheme, token] = normalizedHeader.split(" ");
    if (!scheme || !token || scheme.toLowerCase() !== "bearer") {
      return null;
    }

    return token;
  }
}
