import {
  Body,
  Controller,
  Get,
  Headers,
  HttpCode,
  Post,
  Req,
  UseGuards,
  BadRequestException,
} from '@nestjs/common';
import { Public } from '@/common/decorators/public.decorator';
import { SkipTransform } from '@/common/decorators/skip-transform.decorator';
import { IngestionTokenGuard } from '../guards/ingestion-token.guard';
import { IngestionBatchDto } from '../dto';
import { AiUsageIngestionService } from '../services/ingestion.service';
import { AiUsagePricingService } from '../services/pricing.service';
import { AiUsageOsPlatform } from '@prisma/client';

@Controller('ai-usage')
@Public() // 绕开 JWT；用自己的 IngestionTokenGuard
export class AiUsageIngestionController {
  constructor(
    private readonly ingestion: AiUsageIngestionService,
    private readonly pricing: AiUsagePricingService,
  ) {}

  @Post('events')
  @UseGuards(IngestionTokenGuard)
  @SkipTransform()
  @HttpCode(202)
  async ingest(
    @Req() req: any,
    @Body() body: IngestionBatchDto,
    @Headers('x-device-id') deviceId: string,
    @Headers('x-hostname') hostname: string,
    @Headers('x-os-user') osUser: string,
    @Headers('x-os-platform') osPlatform: string,
    @Headers('x-agent-version') agentVersion: string,
  ) {
    if (!deviceId || !hostname || !osPlatform) {
      throw new BadRequestException('AI_USAGE_INVALID_PAYLOAD');
    }
    const platform = osPlatform.toUpperCase() as AiUsageOsPlatform;
    if (!['LINUX', 'DARWIN', 'WINDOWS'].includes(platform)) {
      throw new BadRequestException('AI_USAGE_INVALID_PAYLOAD');
    }

    const ctxToken = req.aiUsageContext;
    const ip = (req.headers['x-forwarded-for'] as string | undefined)?.split(',')[0]?.trim() ?? req.ip;
    const result = await this.ingestion.ingest({
      tokenId: ctxToken.id,
      userId: ctxToken.userId,
      organizationId: ctxToken.organizationId,
      deviceMeta: { deviceId, hostname, osUser, osPlatform: platform, agentVersion },
      ip,
      body,
    });
    req.res?.setHeader('X-Pricing-Version', this.pricing.getVersion());
    return { success: true, data: result };
  }

  @Get('pricing')
  @SkipTransform()
  async getPricing() {
    return { success: true, data: this.pricing.load() };
  }
}
