/**
 * REST controller for per-tenant agent configuration (engine, prompt, turns, budget, tools).
 *
 * Endpoints (JWT validated by Kong gateway):
 *   GET    /api/v1/agent-config          → Get current tenant's config (returns defaults if none set)
 *   POST   /api/v1/agent-config          → Create new config
 *   PUT    /api/v1/agent-config/:id      → Update existing config
 */
import { Controller, Get, Post, Put, Body, Param, Headers } from '@nestjs/common';
import { AgentConfigService, UpdateAgentConfigDto } from '../../../infrastructure/services/agent-config.service';

const DEFAULT_CONFIG = {
  engine: 'claude-cli',
  system_prompt: '',
  max_turns: 10,
  max_budget: 5.0,
  allowed_tools: ['Bash', 'Read', 'Write', 'Glob', 'Grep'],
};

@Controller('api/v1/agent-config')
export class AgentConfigController {
  constructor(private readonly configService: AgentConfigService) {}

  @Get()
  async getConfig(@Headers('x-tenant-id') tenantId: string) {
    if (!tenantId) return DEFAULT_CONFIG;
    const config = await this.configService.findByTenantId(tenantId);
    if (!config) return DEFAULT_CONFIG;

    return {
      id: config.id,
      engine: config.engine,
      system_prompt: config.systemPrompt,
      max_turns: config.maxTurns,
      max_budget: config.maxBudget,
      allowed_tools: config.allowedTools,
    };
  }

  @Post()
  async createConfig(
    @Headers('x-tenant-id') tenantId: string,
    @Body() dto: UpdateAgentConfigDto,
  ) {
    const config = await this.configService.create(tenantId || 'default', dto);
    return {
      id: config.id,
      engine: config.engine,
      system_prompt: config.systemPrompt,
      max_turns: config.maxTurns,
      max_budget: config.maxBudget,
      allowed_tools: config.allowedTools,
    };
  }

  @Put(':id')
  async updateConfig(
    @Headers('x-tenant-id') tenantId: string,
    @Param('id') id: string,
    @Body() dto: UpdateAgentConfigDto,
  ) {
    const config = await this.configService.update(id, tenantId || 'default', dto);
    if (!config) {
      return { error: 'Config not found' };
    }
    return {
      id: config.id,
      engine: config.engine,
      system_prompt: config.systemPrompt,
      max_turns: config.maxTurns,
      max_budget: config.maxBudget,
      allowed_tools: config.allowedTools,
    };
  }
}
