import {
  Controller,
  Post,
  Get,
  Body,
  HttpCode,
  HttpStatus,
  ForbiddenException,
} from "@nestjs/common";
import {
  ApiTags,
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
} from "@nestjs/swagger";
import { AnalysisService } from "./analysis.service";
import { AnalyzeMatchesDto } from "./dto/analysis-request.dto";
import { CurrentUser } from "../../common/decorators";

@ApiTags("Analysis")
@ApiBearerAuth()
@Controller("analysis")
export class AnalysisController {
  constructor(private readonly analysisService: AnalysisService) {}

  /**
   * POST /analysis/analyze-matches
   * Analyze multiple matches (coupon generation)
   */
  @Post("analyze-matches")
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: "Analyze multiple matches for coupon" })
  @ApiResponse({
    status: 200,
    description: "Analysis successful",
    schema: {
      type: "object",
      properties: {
        success: { type: "boolean" },
        data: { type: "object" },
        message: { type: "string" },
      },
    },
  })
  @ApiResponse({ status: 400, description: "Invalid input" })
  @ApiResponse({ status: 429, description: "Usage limit exceeded" })
  async analyzeMatches(
    @CurrentUser() user: any,
    @Body() dto: AnalyzeMatchesDto,
  ) {
    const { matchIds } = dto;

    // Check usage limit
    const isCoupon = matchIds.length > 1;
    const canProceed = await this.analysisService.checkUsageLimit(
      user.id,
      isCoupon,
      matchIds.length,
    );

    if (!canProceed) {
      throw new ForbiddenException("USAGE_LIMIT_EXCEEDED");
    }

    // Run analysis
    const result = await this.analysisService.analyzeCoupon(matchIds, user.id);

    if (!result) {
      return {
        success: false,
        message: "ANALYSIS_FAILED",
      };
    }

    // Record usage
    await this.analysisService.recordUsage(user.id, isCoupon);

    return {
      success: true,
      data: result,
    };
  }

  /**
   * POST /analysis/analyze (alias for /analyze-matches - frontend compatibility)
   */
  @Post("analyze")
  @HttpCode(HttpStatus.OK)
  @ApiOperation({
    summary: "Analyze multiple matches for coupon (alias)",
    deprecated: true,
  })
  async analyzeMatchesAlias(
    @CurrentUser() user: any,
    @Body() dto: AnalyzeMatchesDto,
  ) {
    return this.analyzeMatches(user, dto);
  }

  /**
   * GET /analysis/history
   * Get user's analysis history
   */
  @Get("history")
  @ApiOperation({ summary: "Get analysis history" })
  @ApiResponse({
    status: 200,
    description: "History retrieved",
    schema: {
      type: "object",
      properties: {
        success: { type: "boolean" },
        data: { type: "array", items: { type: "object" } },
      },
    },
  })
  async getHistory(@CurrentUser() user: any) {
    const history = await this.analysisService.getAnalysisHistory(user.id);
    return { success: true, data: history };
  }
}
