package com.dora.controller;

import com.dora.dto.PromotionRuleDto;
import com.dora.service.PromotionRuleService;
import com.dora.util.JwtUtil;
import com.dora.common.Result;
import io.swagger.v3.oas.annotations.Operation;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 推广规则控制器
 */
@Slf4j
@RestController
@RequestMapping("/user/v1/promotion-rules")
@RequiredArgsConstructor
@Tag(name = "推广规则", description = "系统推广规则相关接口")
public class PromotionRuleController {

    private final PromotionRuleService promotionRuleService;
    private final JwtUtil jwtUtil;

    /**
     * 获取系统推广规则
     */
    @GetMapping
    @Operation(summary = "获取系统推广规则", description = "获取系统推广等级规则和内容收益规则")
    public PromotionRuleDto.PromotionRuleResponse getPromotionRules() {
        return promotionRuleService.getPromotionRules();
    }

    /**
     * 获取用户推广状态实时信息
     */
    @GetMapping("/user-status")
    @Operation(summary = "获取用户推广状态", description = "获取当前用户的推广等级、粉丝数量、下一等级要求等实时信息")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<PromotionRuleDto.UserPromotionStatus>> getUserPromotionStatus(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            PromotionRuleDto.UserPromotionStatus status = promotionRuleService.getUserPromotionStatus(userId);
            return ResponseEntity.ok(Result.success(status, "获取用户推广状态成功"));
        } 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);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, e.getMessage()));
        } catch (Exception e) {
            log.error("获取用户推广状态失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(Result.error(500, "服务器内部错误"));
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            throw new RuntimeException("未提供认证令牌");
        }

        String token = authHeader.substring(7);
        if (!jwtUtil.validateToken(token)) {
            throw new RuntimeException("认证令牌无效或已过期");
        }

        return jwtUtil.getUserIdFromToken(token);
    }
} 