import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Patch,
  Post,
  Query,
  BadRequestException,
} from '@nestjs/common';
import { AiConfigService } from './ai-config.service';
import {
  UpsertProviderDto,
  TestProviderDto,
  ActivateProviderDto,
} from './dto/update-ai-config.dto';
import { createProvider } from '../ai/providers/factory';

@Controller('config/ai')
export class AiConfigController {
  constructor(private readonly svc: AiConfigService) {}

  @Get()
  async get() {
    return this.svc.getPublic();
  }

  /**
   * 创建或更新一个提供商
   */
  @Patch('providers')
  async upsert(@Body() dto: UpsertProviderDto) {
    return this.svc.upsertProvider(dto, dto.operator);
  }

  /**
   * 删除提供商
   */
  @Delete('providers/:id')
  async remove(@Param('id') id: string, @Query('operator') operator?: string) {
    return this.svc.deleteProvider(id, operator);
  }

  /**
   * 切换激活提供商
   */
  @Post('activate')
  async activate(@Body() dto: ActivateProviderDto) {
    return this.svc.activate(dto.id, dto.operator);
  }

  /**
   * 测试某个提供商连通性
   */
  @Post('test')
  async test(@Body() dto: TestProviderDto) {
    if (!dto.id) throw new BadRequestException('id 必填');
    const fullProvider = await this.svc.getProviderFullById(dto.id);
    if (!fullProvider) throw new BadRequestException('提供商不存在');

    try {
      const provider = createProvider(fullProvider);
      const r = await provider.ping({ model: fullProvider.model });
      return {
        ok: true,
        message: `连接成功（${fullProvider.model} · 输入 ${r.inputTokens}tok 输出 ${r.outputTokens}tok）`,
      };
    } catch (e: any) {
      return {
        ok: false,
        error: e?.message || '调用失败',
      };
    }
  }
}
