package com.dora.controller;

import com.dora.common.Result;
import com.dora.entity.PointsPackage;
import com.dora.service.AdminPointsPackageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 管理端积分套餐控制器
 * 
 * 提供以下功能：
 * 1. 积分套餐管理（增删改查）
 * 2. 套餐状态管理（上架/下架）
 * 3. 套餐排序管理
 * 4. 套餐统计信息
 * 
 * @author 1818AI
 * @since 2025-10-24
 */
@Slf4j
@RestController
@RequestMapping("/admin/points/packages")
@Tag(name = "积分套餐管理", description = "管理端API - 用于管理积分充值套餐")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ADMIN')")
public class AdminPointsPackageController {

    private final AdminPointsPackageService adminPointsPackageService;

    /**
     * 获取所有积分套餐
     */
    @GetMapping
    @Operation(
        summary = "获取所有积分套餐", 
        description = "查询所有积分套餐列表，包括已上架和已下架的套餐"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "401", description = "未授权 - 需要管理员登录"),
        @ApiResponse(responseCode = "403", description = "禁止访问 - 需要ADMIN角色")
    })
    public Result<List<PointsPackage>> getAllPackages() {
        try {
            List<PointsPackage> packages = adminPointsPackageService.getAllPackages();
            return Result.success(packages);
        } catch (Exception e) {
            log.error("获取积分套餐列表失败", e);
            return Result.error("获取套餐列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取套餐详情
     */
    @GetMapping("/{id}")
    @Operation(
        summary = "获取套餐详情", 
        description = "根据ID获取积分套餐的详细信息"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "套餐不存在"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "403", description = "禁止访问")
    })
    public Result<PointsPackage> getPackageById(
            @Parameter(description = "套餐ID", required = true, example = "1")
            @PathVariable Long id) {
        try {
            PointsPackage pointsPackage = adminPointsPackageService.getPackageById(id);
            return Result.success(pointsPackage);
        } catch (Exception e) {
            log.error("获取积分套餐详情失败 - id: {}", id, e);
            return Result.error("获取套餐详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建新的积分套餐
     */
    @PostMapping
    @Operation(
        summary = "创建积分套餐", 
        description = "创建新的积分充值套餐。系统会自动计算总积分（基础积分+赠送积分）。"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "创建成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误 - 必填字段缺失或格式错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "403", description = "禁止访问")
    })
    public Result<PointsPackage> createPackage(
            @Parameter(description = "积分套餐信息", required = true)
            @Valid @RequestBody PointsPackage pointsPackage) {
        try {
            PointsPackage createdPackage = adminPointsPackageService.createPackage(pointsPackage);
            return Result.success(createdPackage, "创建成功");
        } catch (Exception e) {
            log.error("创建积分套餐失败", e);
            return Result.error("创建套餐失败：" + e.getMessage());
        }
    }

    /**
     * 更新积分套餐
     */
    @PutMapping("/{id}")
    @Operation(
        summary = "更新积分套餐", 
        description = "修改指定积分套餐的信息。常用于调整套餐价格、积分数量、描述等。"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "404", description = "未找到指定的套餐"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "403", description = "禁止访问")
    })
    public Result<PointsPackage> updatePackage(
            @Parameter(description = "套餐ID", required = true, example = "1")
            @PathVariable Long id,
            @Parameter(description = "更新的套餐信息", required = true)
            @Valid @RequestBody PointsPackage pointsPackage) {
        try {
            PointsPackage updatedPackage = adminPointsPackageService.updatePackage(id, pointsPackage);
            return Result.success(updatedPackage, "更新成功");
        } catch (Exception e) {
            log.error("更新积分套餐失败 - id: {}", id, e);
            return Result.error("更新套餐失败：" + e.getMessage());
        }
    }

    /**
     * 更新套餐状态（上架/下架）
     */
    @PutMapping("/{id}/status")
    @Operation(
        summary = "更新套餐状态", 
        description = "设置指定积分套餐的上架状态。下架后的套餐用户无法购买。"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "状态值错误"),
        @ApiResponse(responseCode = "404", description = "未找到指定的套餐"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "403", description = "禁止访问")
    })
    public Result<Void> updatePackageStatus(
            @Parameter(description = "套餐ID", required = true, example = "1")
            @PathVariable Long id,
            @Parameter(description = "是否上架（1-上架，0-下架）", required = true, example = "1")
            @RequestParam Integer isActive) {
        try {
            adminPointsPackageService.updatePackageStatus(id, isActive);
            String statusText = isActive == 1 ? "上架" : "下架";
            return Result.success(null, statusText + "成功");
        } catch (Exception e) {
            log.error("更新积分套餐状态失败 - id: {}, isActive: {}", id, isActive, e);
            return Result.error("更新套餐状态失败：" + e.getMessage());
        }
    }

    /**
     * 删除积分套餐
     */
    @DeleteMapping("/{id}")
    @Operation(
        summary = "删除积分套餐", 
        description = "逻辑删除指定的积分套餐。删除后该套餐将无法被用户购买。注意：这是软删除，数据库记录仍然保留。"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "404", description = "未找到指定的套餐"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "403", description = "禁止访问")
    })
    public Result<Void> deletePackage(
            @Parameter(description = "套餐ID", required = true, example = "1")
            @PathVariable Long id) {
        try {
            adminPointsPackageService.deletePackage(id);
            return Result.success(null, "删除成功");
        } catch (Exception e) {
            log.error("删除积分套餐失败 - id: {}", id, e);
            return Result.error("删除套餐失败：" + e.getMessage());
        }
    }

    /**
     * 批量更新套餐排序
     */
    @PutMapping("/sort")
    @Operation(
        summary = "批量更新套餐排序", 
        description = "根据提供的套餐ID顺序更新排序。前端展示时会按照排序值升序显示。"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误 - ID列表为空"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "403", description = "禁止访问")
    })
    public Result<Void> updatePackageSort(
            @Parameter(
                description = "套餐ID列表，按照期望的排序顺序排列", 
                required = true,
                example = "[1, 3, 2, 4]"
            )
            @RequestBody Map<String, List<Long>> request) {
        try {
            List<Long> packageIds = request.get("packageIds");
            if (packageIds == null || packageIds.isEmpty()) {
                return Result.error("套餐ID列表不能为空");
            }
            
            adminPointsPackageService.updatePackageSort(packageIds);
            return Result.success(null, "排序更新成功");
        } catch (Exception e) {
            log.error("批量更新套餐排序失败", e);
            return Result.error("更新排序失败：" + e.getMessage());
        }
    }

    /**
     * 获取套餐统计信息
     */
    @GetMapping("/stats")
    @Operation(
        summary = "获取套餐统计信息", 
        description = "获取积分套餐的统计数据，包括总数量、上架数量、热门推荐数量等。"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "403", description = "禁止访问")
    })
    public Result<AdminPointsPackageService.PackageStatsResponse> getPackageStats() {
        try {
            AdminPointsPackageService.PackageStatsResponse stats = adminPointsPackageService.getPackageStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取套餐统计信息失败", e);
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }
}
