/**
 * Admin REST controller for per-tenant Agent SDK configuration.
 *
 * Endpoints (JWT validated by Kong gateway):
 *   GET    /api/v1/agent/tenant-config          → Get current tenant's SDK config (returns defaults if none set)
 *   PUT    /api/v1/agent/tenant-config          → Create/update config (billingMode, apiKey, timeout, tools)
 *   DELETE /api/v1/agent/tenant-config/api-key  → Remove API key, revert to subscription billing
 *
 * Note: API key is never returned in responses — only `hasApiKey: boolean` is exposed.
 */
import { Controller, Get, Put, Delete, Body, Headers, NotFoundException } from '@nestjs/common';
import { TenantAgentConfigService, UpdateTenantAgentConfigDto } from '../../../infrastructure/services/tenant-agent-config.service';

@Controller('api/v1/agent/tenant-config')
export class TenantAgentConfigController {
  constructor(
    private readonly tenantConfigService: TenantAgentConfigService,
  ) {}

  @Get()
  async getConfig(@Headers('x-tenant-id') tenantId: string) {
    if (!tenantId) {
      return {
        tenantId: '',
        billingMode: 'subscription',
        approvalTimeoutSeconds: 120,
        toolWhitelist: [],
        toolBlacklist: [],
        hasApiKey: false,
      };
    }

    const config = await this.tenantConfigService.findByTenantId(tenantId);
    if (!config) {
      return {
        tenantId,
        billingMode: 'subscription',
        approvalTimeoutSeconds: 120,
        toolWhitelist: [],
        toolBlacklist: [],
        hasApiKey: false,
      };
    }

    return {
      tenantId: config.tenantId,
      billingMode: config.billingMode,
      approvalTimeoutSeconds: config.approvalTimeoutSeconds,
      toolWhitelist: config.toolWhitelist,
      toolBlacklist: config.toolBlacklist,
      hasApiKey: config.encryptedApiKey !== null,
      createdAt: config.createdAt,
      updatedAt: config.updatedAt,
    };
  }

  @Put()
  async upsertConfig(
    @Headers('x-tenant-id') tenantId: string,
    @Body() dto: UpdateTenantAgentConfigDto,
  ) {
    const config = await this.tenantConfigService.upsert(tenantId || 'default', dto);
    return {
      tenantId: config.tenantId,
      billingMode: config.billingMode,
      approvalTimeoutSeconds: config.approvalTimeoutSeconds,
      toolWhitelist: config.toolWhitelist,
      toolBlacklist: config.toolBlacklist,
      hasApiKey: config.encryptedApiKey !== null,
      updatedAt: config.updatedAt,
    };
  }

  @Delete('api-key')
  async removeApiKey(@Headers('x-tenant-id') tenantId: string) {
    const config = await this.tenantConfigService.removeApiKey(tenantId || 'default');
    if (!config) {
      throw new NotFoundException('No agent config found for this tenant');
    }
    return {
      message: 'API key removed, reverted to subscription billing',
      billingMode: config.billingMode,
    };
  }
}
