import {
  Controller,
  ForbiddenException,
  Get,
  Param,
  Req,
  UnauthorizedException,
  UseGuards,
} from "@nestjs/common";
import { AgentConfigService } from "./agent-config.service";
import { AgentConfigGuard, type AgentConfigRequest } from "./agent-config.guard";

@Controller("internal")
@UseGuards(AgentConfigGuard)
export class AgentConfigController {
  constructor(private readonly agentConfigService: AgentConfigService) {}

  // GET /api/internal/agent-config/:id
  // Auth: Bearer token (validated against UserContainer.gatewayToken or SystemContainer.gatewayToken)
  // Returns: assembled openclaw.json
  //
  // The :id param is the container record ID (cuid)
  // Token must match the container requesting its own config
  @Get("agent-config/:id")
  async getAgentConfig(
    @Param("id") id: string,
    @Req() request: AgentConfigRequest
  ): Promise<object> {
    const containerAuth = request.containerAuth;
    if (!containerAuth) {
      throw new UnauthorizedException("Missing container authentication context");
    }

    if (containerAuth.id !== id) {
      throw new ForbiddenException("Token is not authorized for the requested container");
    }

    return this.agentConfigService.generateConfigForContainer(containerAuth.type, id);
  }
}
