package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.PointsRechargeDto;
import com.dora.service.PointsRechargeService;
import com.dora.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 积分充值控制器（用户端）
 */
@Slf4j
@RestController
@RequestMapping("/user/points")
@Tag(name = "积分充值管理（用户端）", description = "用户积分充值相关接口")
@RequiredArgsConstructor
public class PointsRechargeController {

    private final PointsRechargeService pointsRechargeService;

    /**
     * 获取积分套餐列表
     */
    @GetMapping("/packages")
    @Operation(summary = "获取积分套餐列表", description = "获取所有上架的积分套餐")
    public Result<List<PointsRechargeDto.PackageResponse>> getPackages() {
        try {
            List<PointsRechargeDto.PackageResponse> packages = pointsRechargeService.getActivePackages();
            return Result.success(packages);
        } catch (Exception e) {
            log.error("获取积分套餐列表失败", e);
            return Result.error("获取套餐列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取热门套餐
     */
    @GetMapping("/packages/hot")
    @Operation(summary = "获取热门套餐", description = "获取推荐的热门积分套餐")
    public Result<List<PointsRechargeDto.PackageResponse>> getHotPackages(
            @Parameter(description = "数量限制", example = "3")
            @RequestParam(defaultValue = "3") Integer limit) {
        try {
            List<PointsRechargeDto.PackageResponse> packages = pointsRechargeService.getHotPackages(limit);
            return Result.success(packages);
        } catch (Exception e) {
            log.error("获取热门套餐失败", e);
            return Result.error("获取热门套餐失败：" + e.getMessage());
        }
    }

    /**
     * 获取套餐详情
     */
    @GetMapping("/packages/{packageId}")
    @Operation(summary = "获取套餐详情", description = "根据ID获取积分套餐详细信息")
    public Result<PointsRechargeDto.PackageResponse> getPackageDetail(
            @Parameter(description = "套餐ID", required = true)
            @PathVariable Long packageId) {
        try {
            PointsRechargeDto.PackageResponse packageInfo = pointsRechargeService.getPackageById(packageId);
            return Result.success(packageInfo);
        } catch (Exception e) {
            log.error("获取套餐详情失败 - packageId: {}", packageId, e);
            return Result.error("获取套餐详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建充值订单
     */
    @PostMapping("/recharge")
    @Operation(summary = "创建充值订单", description = "创建积分充值订单并返回支付参数")
    public Result<PointsRechargeDto.CreateRechargeOrderResponse> createRechargeOrder(
            @Valid @RequestBody PointsRechargeDto.CreateRechargeOrderRequest request) {
        try {
            // 获取当前用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            
            // 创建充值订单
            PointsRechargeDto.CreateRechargeOrderResponse response = 
                pointsRechargeService.createRechargeOrder(currentUserId, request);
            
            return Result.success(response);
        } catch (AuthenticationException e) {
            log.error("用户未登录", e);
            return Result.error(401, "请先登录");
        } catch (Exception e) {
            log.error("创建充值订单失败", e);
            return Result.error("创建订单失败：" + e.getMessage());
        }
    }

    /**
     * 获取充值记录
     */
    @GetMapping("/recharge/records")
    @Operation(summary = "获取充值记录", description = "获取用户的积分充值历史记录")
    public Result<List<PointsRechargeDto.RechargeRecordResponse>> getRechargeRecords(
            @Parameter(description = "页码", example = "1")
            @RequestParam(defaultValue = "1") Integer page,
            @Parameter(description = "每页数量", example = "10")
            @RequestParam(defaultValue = "10") Integer size) {
        try {
            Long currentUserId = SecurityUtil.getCurrentUserId();
            
            List<PointsRechargeDto.RechargeRecordResponse> records = 
                pointsRechargeService.getRechargeRecords(currentUserId, page, size);
            
            return Result.success(records);
        } catch (AuthenticationException e) {
            log.error("用户未登录", e);
            return Result.error(401, "请先登录");
        } catch (Exception e) {
            log.error("获取充值记录失败", e);
            return Result.error("获取充值记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取充值统计
     */
    @GetMapping("/recharge/stats")
    @Operation(summary = "获取充值统计", description = "获取用户的积分充值统计信息")
    public Result<PointsRechargeDto.RechargeStatsResponse> getRechargeStats() {
        try {
            Long currentUserId = SecurityUtil.getCurrentUserId();
            
            PointsRechargeDto.RechargeStatsResponse stats = 
                pointsRechargeService.getRechargeStats(currentUserId);
            
            return Result.success(stats);
        } catch (AuthenticationException e) {
            log.error("用户未登录", e);
            return Result.error(401, "请先登录");
        } catch (Exception e) {
            log.error("获取充值统计失败", e);
            return Result.error("获取充值统计失败：" + e.getMessage());
        }
    }
}

