import { Controller, Get, Param, Query } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ZodResponse } from 'nestjs-zod';
import { Permission } from '@pac/types';
import { RequirePermission } from '../../common/decorators/permissions.decorator';
import {
  TenantScope,
  TenantScopeContext,
} from '../../common/decorators/tenant-scope.decorator';
import {
  AiInvocationDetailDto,
  AiInvocationListQueryDto,
  AiInvocationStatsDto,
  ListAiInvocationsResponseDto,
} from './dto/admin.dto';
import { AiInvocationsService } from './ai-invocations.service';

/**
 * AI Invocations debug — /admin/ai-invocations
 *
 * 给运维 / prompt 调优者用:
 *   - 看历史调用(谁、什么 prompt、输入输出、cost)
 *   - 按 callKey / promptVersion 横向比较(同 input 不同版本效果)
 *   - 24h 成本仪表 / 失败率监控
 *
 * Scope:host self(只能看自家 host_id 下的调用)。权限 PLATFORM_MANAGE。
 */
@ApiTags('admin')
@ApiBearerAuth('accessToken')
@Controller('admin/ai-invocations')
@RequirePermission(Permission.PLATFORM_MANAGE)
export class AiInvocationsAdminController {
  constructor(private readonly invocations: AiInvocationsService) {}

  @Get()
  @ZodResponse({ status: 200, type: ListAiInvocationsResponseDto })
  @ApiOperation({ summary: 'AI 调用列表(分页 + 筛选)' })
  list(
    @TenantScope() scope: TenantScopeContext,
    @Query() query: AiInvocationListQueryDto,
  ) {
    return this.invocations.list(scope, query);
  }

  @Get('stats')
  @ZodResponse({ status: 200, type: AiInvocationStatsDto })
  @ApiOperation({ summary: '24h 调用总览 + 按 callKey 分组热点' })
  stats(@TenantScope() scope: TenantScopeContext) {
    return this.invocations.stats(scope);
  }

  @Get(':id')
  @ZodResponse({ status: 200, type: AiInvocationDetailDto })
  @ApiOperation({ summary: 'AI 调用详情(含 inputSnapshot / promptTemplate / output)' })
  detail(@TenantScope() scope: TenantScopeContext, @Param('id') id: string) {
    return this.invocations.detail(scope, id);
  }
}
