import { Controller, Get, Post, Patch, Delete, Body, Param, Query, Res, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import type { Response } from 'express';
import { AdminCostsService } from './admin-costs.service';
import { CostAggregationService } from './cost-aggregation.service';
import { AdminAuthGuard } from '../../common/guards/admin-auth.guard';
import { AdminRoles } from '../../common/decorators/admin-roles.decorator';
import type { AdminRole } from '../../common/types/admin-role.enum';

@ApiTags('admin-costs')
@Controller('admin-api/costs')
@UseGuards(AdminAuthGuard)
@ApiBearerAuth()
export class AdminCostsController {
  constructor(
    private readonly svc: AdminCostsService,
    private readonly costAgg: CostAggregationService,
  ) {}

  @Get() @AdminRoles('SUPER_ADMIN' as AdminRole) async list() { return this.svc.list(); }
  @Get('summary') @AdminRoles('SUPER_ADMIN' as AdminRole) async summary() { return this.svc.summary(); }
  @Post() @AdminRoles('SUPER_ADMIN' as AdminRole) async create(@Body() d: any) { return this.svc.create(d); }
  @Patch(':id') @AdminRoles('SUPER_ADMIN' as AdminRole) async update(@Param('id') id: string, @Body() d: any) { return this.svc.update(id, d); }
  @Delete(':id') @AdminRoles('SUPER_ADMIN' as AdminRole) async delete(@Param('id') id: string) { return this.svc.delete(id); }

  // ── AI Cost Report ──

  @Get('report')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: 'AI 成本报表（按provider/模型/日趋势）' })
  async report(@Query('days') days = '30') {
    return this.costAgg.getReport(parseInt(days));
  }

  @Post('aggregate')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: '手动触发成本汇总' })
  async aggregate() {
    await this.costAgg.aggregateToday();
    return { success: true };
  }

  @Get('export-csv')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: '导出成本 CSV' })
  async exportCsv(@Query('days') days = '30', @Res() res: Response) {
    const csv = await this.costAgg.exportCsv(parseInt(days));
    res.setHeader('Content-Type', 'text/csv; charset=utf-8');
    res.setHeader('Content-Disposition', `attachment; filename="cost-report-${days}d.csv"`);
    res.send(csv);
  }

  // ── Top consumers ──

  @Get('top-users')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  @ApiOperation({ summary: 'Top 消耗用户' })
  async topUsers(@Query('days') days = '30', @Query('limit') limit = '10') {
    const since = new Date(Date.now() - parseInt(days) * 86400000);
    const top = await this.svc.getTopConsumers(since, parseInt(limit));
    return { top, days: parseInt(days) };
  }
}
