package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.GiftCodeDto;
import com.dora.service.GiftCodeService;
import com.dora.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
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 jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 礼品码管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/user/gift")
@RequiredArgsConstructor
@Tag(name = "礼品码管理", description = "礼品码兑换相关接口")
public class GiftCodeController {

    private final GiftCodeService giftCodeService;
    private final JwtUtil jwtUtil;

    @PostMapping("/redeem")
    @Operation(summary = "兑换礼品码", description = "使用礼品码进行充值或升级会员")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "兑换成功",
            content = @Content(schema = @Schema(implementation = GiftCodeDto.RedeemResponse.class))),
        @ApiResponse(responseCode = "400", description = "兑换失败"),
        @ApiResponse(responseCode = "401", description = "未登录"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<GiftCodeDto.RedeemResponse>> redeemGiftCode(
            @Valid @RequestBody GiftCodeDto.RedeemRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            GiftCodeDto.RedeemResponse response = giftCodeService.redeemGiftCode(userId, request.getCode());
            
            if (response.getSuccess()) {
                return ResponseEntity.ok(Result.success(response, response.getMessage()));
            } else {
                return ResponseEntity.badRequest().body(Result.error(400, response.getMessage()));
            }
        } 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);
    }
} 