import { Controller, Get, Post, Param, Body, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiBody } from '@nestjs/swagger';
import { CacheService } from '../../common/cache/cache.service';
import { AdminAuthGuard } from '../../common/guards/admin-auth.guard';
import { AdminRolesGuard } from '../../common/guards/admin-roles.guard';

@ApiTags('admin-cache')
@ApiBearerAuth()
@Controller('admin-api/cache')
@UseGuards(AdminAuthGuard, AdminRolesGuard)
export class AdminCacheController {
  constructor(private readonly cacheService: CacheService) {}

  @Get('stats')
  @ApiOperation({ summary: '缓存统计' })
  async getStats() {
    return this.cacheService.getStats();
  }

  @Post('flush/:module')
  @ApiOperation({ summary: '按模块清除缓存' })
  async flushModule(@Param('module') module: string) {
    const count = await this.cacheService.flushPattern(`${module}:*`);
    return { flushed: count, module };
  }

  @Post('flush-key')
  @ApiOperation({ summary: '清除指定缓存 key' })
  @ApiBody({ schema: { type: 'object', required: ['key'], properties: { key: { type: 'string' } } } })
  async flushKey(@Body() body: { key: string }) {
    await this.cacheService.del(body.key);
    return { ok: true, key: body.key };
  }

  @Post('flush-all')
  @ApiOperation({ summary: '清除所有缓存' })
  async flushAll() {
    const count = await this.cacheService.flushAll();
    return { flushed: count };
  }

  @Post('reset-stats')
  @ApiOperation({ summary: '重置缓存统计' })
  async resetStats() {
    this.cacheService.resetStats();
    return this.cacheService.getStats();
  }
}
