package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.FanDto;
import com.dora.dto.FanListResponseDto;
import com.dora.dto.PromotionDto;
import com.dora.service.PromotionService;
import com.dora.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
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.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 推广控制器
 */
@RestController
@RequestMapping("/user/promotion")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "推广管理", description = "用户推广码和粉丝管理相关接口")
public class PromotionController {

    private final PromotionService promotionService;
    private final JwtUtil jwtUtil;

    /**
     * 生成用户专属推广码
     *
     * @param request HTTP请求
     * @return 推广码
     */
    @PostMapping("/generate-invite-code")
    @Operation(summary = "生成用户专属推广码", description = "为用户生成唯一的推广码")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功", 
            content = @Content(schema = @Schema(implementation = Result.class))),
        @ApiResponse(responseCode = "400", description = "生成失败"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<String>> generateInviteCode(HttpServletRequest request) {
        try {
            // 从JWT中获取用户ID（这里需要根据你的JWT工具类调整）
            Long userId = getUserIdFromRequest(request);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error(401, "用户未登录"));
            }

            String inviteCode = promotionService.generateInviteCode(userId);
            return ResponseEntity.ok(Result.success(inviteCode, "推广码生成成功"));
            
        } catch (RuntimeException e) {
            // JWT相关异常返回401
            if (e.getMessage().contains("认证令牌") || e.getMessage().contains("未提供认证令牌")) {
                log.warn("JWT认证失败: {}", e.getMessage());
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error(401, e.getMessage()));
            }
            log.error("生成推广码失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, e.getMessage()));
        } catch (Exception e) {
            log.error("生成推广码失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, "生成推广码失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户推广信息
     *
     * @param request HTTP请求
     * @return 推广信息
     */
    @GetMapping("/my")
    @Operation(summary = "获取我的推广信息", description = "获取当前用户的推广码、粉丝统计、提成信息等")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功", 
            content = @Content(schema = @Schema(implementation = Result.class))),
        @ApiResponse(responseCode = "400", description = "获取失败"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<PromotionDto>> getMyPromotionInfo(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error(401, "用户未登录"));
            }

            PromotionDto promotionInfo = promotionService.getPromotionInfo(userId);
            return ResponseEntity.ok(Result.success(promotionInfo, "获取推广信息成功"));
            
        } catch (RuntimeException e) {
            // JWT相关异常返回401
            if (e.getMessage().contains("认证令牌") || e.getMessage().contains("未提供认证令牌")) {
                log.warn("JWT认证失败: {}", e.getMessage());
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error(401, e.getMessage()));
            }
            log.error("获取推广信息失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, e.getMessage()));
        } catch (Exception e) {
            log.error("获取推广信息失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, "获取推广信息失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户粉丝列表（包含统计信息）
     *
     * @param request HTTP请求
     * @param page 页码
     * @param size 每页大小
     * @param status 粉丝状态（paid-当前付费会员，gift-赠送会员，exchange-当前兑换会员，expired-过期会员，none-非VIP，all-所有粉丝）
     * @return 粉丝列表响应（包含统计信息）
     */
    @GetMapping("/fans")
    @Operation(summary = "获取我的粉丝列表", description = "获取当前用户的粉丝列表，包含统计信息，支持筛选不同类型的会员状态（会自动检查会员有效期）")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功", 
            content = @Content(schema = @Schema(implementation = Result.class))),
        @ApiResponse(responseCode = "400", description = "获取失败"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<FanListResponseDto>> getFansListWithStats(
            HttpServletRequest request,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "粉丝状态：paid-当前付费会员，gift-赠送会员，exchange-当前兑换会员，expired-过期会员，none-非VIP，all-所有粉丝", example = "all") @RequestParam(defaultValue = "all") String status) {
        try {
            Long userId = getUserIdFromRequest(request);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error(401, "用户未登录"));
            }

            FanListResponseDto fansResponse = promotionService.getFansListWithStats(userId, page, size, status);
            return ResponseEntity.ok(Result.success(fansResponse, "获取粉丝列表成功"));
            
        } catch (RuntimeException e) {
            // JWT相关异常返回401
            if (e.getMessage().contains("认证令牌") || e.getMessage().contains("未提供认证令牌")) {
                log.warn("JWT认证失败: {}", e.getMessage());
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error(401, e.getMessage()));
            }
            log.error("获取粉丝列表失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, e.getMessage()));
        } catch (Exception e) {
            log.error("获取粉丝列表失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, "获取粉丝列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户粉丝列表（兼容旧接口）
     *
     * @param request HTTP请求
     * @param page 页码
     * @param size 每页大小
     * @param status 粉丝状态（paid-当前付费会员，gift-赠送会员，exchange-当前兑换会员，expired-过期会员，none-非VIP，all-所有粉丝）
     * @return 粉丝列表
     */
    @GetMapping("/fans/old")
    @Operation(summary = "获取我的粉丝列表（旧接口）", description = "获取当前用户的粉丝列表，支持筛选不同类型的会员状态")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功", 
            content = @Content(schema = @Schema(implementation = Result.class))),
        @ApiResponse(responseCode = "400", description = "获取失败"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<List<FanDto>>> getFansList(
            HttpServletRequest request,
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "粉丝状态：paid-当前付费会员，gift-赠送会员，exchange-当前兑换会员，expired-过期会员，none-非VIP，all-所有粉丝", example = "all") @RequestParam(defaultValue = "all") String status) {
        try {
            Long userId = getUserIdFromRequest(request);
            if (userId == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error(401, "用户未登录"));
            }

            List<FanDto> fans = promotionService.getFansList(userId, page, size, status);
            return ResponseEntity.ok(Result.success(fans, "获取粉丝列表成功"));
            
        } catch (RuntimeException e) {
            // JWT相关异常返回401
            if (e.getMessage().contains("认证令牌") || e.getMessage().contains("未提供认证令牌")) {
                log.warn("JWT认证失败: {}", e.getMessage());
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Result.error(401, e.getMessage()));
            }
            log.error("获取粉丝列表失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, e.getMessage()));
        } catch (Exception e) {
            log.error("获取粉丝列表失败: {}", e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, "获取粉丝列表失败: " + e.getMessage()));
        }
    }

    /**
     * 验证推广码
     *
     * @param inviteCode 推广码
     * @return 验证结果
     */
    @GetMapping("/validate-invite-code")
    @Operation(summary = "验证推广码", description = "验证推广码是否有效")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "成功", 
            content = @Content(schema = @Schema(implementation = Result.class))),
        @ApiResponse(responseCode = "400", description = "验证失败"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public Result<Boolean> validateInviteCode(
            @Parameter(description = "推广码", required = true) @RequestParam String inviteCode) {
        try {
            boolean isValid = promotionService.validateInviteCode(inviteCode);
            return Result.success(isValid, isValid ? "推广码有效" : "推广码无效");
            
        } catch (Exception e) {
            log.error("验证推广码失败: {}", e.getMessage(), e);
            return Result.error(400, "验证推广码失败: " + e.getMessage());
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            if (jwtUtil.validateToken(token)) {
                return jwtUtil.getUserIdFromToken(token);
            }
        }
        return null;
    }
} 