package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.WithdrawDto;
import com.dora.service.UserBalanceService;
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 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.*;

/**
 * 提现控制器
 */
@RestController
@RequestMapping("/user/withdraw")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "提现管理", description = "提现相关接口")
public class WithdrawController {

    private final UserBalanceService userBalanceService;
    private final JwtUtil jwtUtil;

    /**
     * 从请求中获取用户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);
    }

    @PostMapping("/submit")
    @Operation(summary = "提交提现申请", description = "从用户余额中提现，需要余额达到100元以上")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "提交成功", 
            content = @Content(schema = @Schema(implementation = WithdrawDto.WithdrawResponse.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<WithdrawDto.WithdrawResponse>> submitWithdraw(
            @Valid @RequestBody WithdrawDto.WithdrawRequest request,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            WithdrawDto.WithdrawResponse response = userBalanceService.submitWithdrawRequest(userId, request);
            return ResponseEntity.ok(Result.success(response, "提现申请提交成功"));
        } 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, "服务器内部错误"));
        }
    }

    @GetMapping("/list")
    @Operation(summary = "获取提现记录列表", description = "获取当前用户的提现记录列表")
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "获取成功", 
            content = @Content(schema = @Schema(implementation = WithdrawDto.WithdrawListResponse.class))),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "未授权"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    public ResponseEntity<Result<WithdrawDto.WithdrawListResponse>> getWithdrawList(
            @Parameter(description = "页码", example = "1") @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页大小", example = "10") @RequestParam(defaultValue = "10") int size,
            HttpServletRequest httpRequest) {
        try {
            Long userId = getUserIdFromRequest(httpRequest);
            WithdrawDto.WithdrawListResponse response = userBalanceService.getWithdrawList(userId, page, size);
            return ResponseEntity.ok(Result.success(response, "获取提现记录成功"));
        } 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, "服务器内部错误"));
        }
    }
} 