import { Controller, Get, Post, Body, Param, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RequirePermission } from '../../auth/decorators/permission.decorator';
import { IntegrationConfigService } from './integration-config.service';
import { SaveIntegrationConfigDto, TestIntegrationConfigDto } from './dto/config.dto';

@Controller('integration/config')
@UseGuards(JwtAuthGuard)
export class IntegrationConfigController {
  constructor(private readonly service: IntegrationConfigService) {}

  /** 获取全部配置（脱敏） */
  @Get()
  @RequirePermission('integration:read')
  async getConfigs() {
    const data = await this.service.getThirdConfig();
    return { success: true, data };
  }

  /** 按类型获取单个配置 */
  @Get(':type')
  @RequirePermission('integration:read')
  async getConfig(@Param('type') type: string) {
    const data = await this.service.getConfigByType(type.toUpperCase());
    if (!data) {
      return { success: false, message: `未找到 ${type} 的配置` };
    }
    return { success: true, data };
  }

  /** 保存配置 */
  @Post()
  @RequirePermission('integration:trigger')
  async saveConfig(@Body() body: SaveIntegrationConfigDto) {
    await this.service.saveConfig(body);
    return { success: true, message: '配置已保存' };
  }

  /** 测试连接 */
  @Post('test')
  @RequirePermission('integration:read')
  async testConnection(@Body() body: TestIntegrationConfigDto) {
    const success = await this.service.testConnection(body.type, body.config);
    return { success, message: success ? '连接成功' : '连接失败，请检查配置信息' };
  }
}
