import { Controller, Get, Post, Patch, Delete, Body, Param, Query, Req, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { AppConfigService } from './config.service';
import { FeatureFlagService } from './feature-flag.service';
import { AdminAuthGuard } from '../../common/guards/admin-auth.guard';
import { AdminRolesGuard } from '../../common/guards/admin-roles.guard';
import { AdminRoles } from '../../common/decorators/admin-roles.decorator';
import type { AdminRole } from '../../common/types/admin-role.enum';

@ApiTags('admin-config')
@Controller('admin-api/config')
@UseGuards(AdminAuthGuard, AdminRolesGuard)
@ApiBearerAuth()
export class AppConfigController {
  constructor(
    private readonly config: AppConfigService,
    private readonly flags: FeatureFlagService,
  ) {}

  @Get()
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: '配置列表' })
  async list() { return { configs: await this.config.getAll(), flags: await this.flags.getAll() } }

  @Post()
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async create(@Body() d: { key: string; value: string; description?: string }, @Req() req: any) {
    await this.config.set(d.key, d.value, req.adminUser?.email);
    return { success: true };
  }

  @Patch(':key')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async update(@Param('key') key: string, @Body() d: { value: string }, @Req() req: any) {
    await this.config.set(key, d.value, req.adminUser?.email);
    return { success: true };
  }

  @Delete(':key')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async remove(@Param('key') key: string) {
    await this.config.delete(key);
    return { success: true };
  }

  @Get('changelog')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async changelog() { return this.config.getChangeLogs(); }

  @Post('flags/:name')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async toggleFlag(@Param('name') name: string, @Body() d: { enabled?: boolean; whitelist?: string }, @Req() req: any) {
    if (typeof d.enabled === 'boolean') {
      await this.flags.setEnabled(name, d.enabled, req.adminUser?.email);
    }
    if (d.whitelist !== undefined) {
      await this.flags.setWhitelist(name, d.whitelist);
    }
    return { success: true };
  }
}
