import { Controller, Get, Post, Param, Body, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { PrismaService } from '../../infrastructure/database/prisma.service';
import { QuotaService } from './quota.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-quota')
@Controller('admin-api/quota')
@UseGuards(AdminAuthGuard, AdminRolesGuard)
@ApiBearerAuth()
export class QuotaController {
  constructor(private readonly prisma: PrismaService, private readonly quota: QuotaService) {}

  @Get('plans')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async plans() { return this.prisma.membershipPlan.findMany() }

  @Post('plans')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async createPlan(@Body() d: any) { return this.prisma.membershipPlan.create({ data: d }) }

  @Get('memberships')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async memberships() { return this.prisma.userMembership.findMany({ include: { user: { select: { email: true } }, plan: true }, orderBy: { createdAt: 'desc' }, take: 50 }) }

  @Get('usage/:userId')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async userUsage(@Param('userId') userId: string) {
    const types = ['ai_call', 'ocr', 'storage', 'vision', 'embedding'];
    const result: Record<string, { used: number; limit: number }> = {};
    for (const t of types) {
      result[t] = { used: await this.quota.getUsed(userId, t), limit: await this.quota.getRemaining(userId, t) + await this.quota.getUsed(userId, t) };
    }
    return result;
  }

  @Get('costs')
  @AdminRoles('SUPER_ADMIN' as AdminRole)
  async costs() { return this.prisma.costDailySummary.findMany({ orderBy: { date: 'desc' }, take: 30 }) }
}
