package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.IdentityVerifyRequestDto;
import com.dora.dto.IdentityVerifyResponseDto;
import com.dora.service.IdentityVerifyService;
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.security.SecurityRequirement;
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.web.bind.annotation.*;

/**
 * 实名认证控制器
 *
 * @author Dora
 */
@Slf4j
@RestController
@RequestMapping("/user/identity")
@RequiredArgsConstructor
@Tag(name = "实名认证", description = "用户实名认证相关接口")
public class IdentityVerifyController {

    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";
    private static final String USER_NOT_LOGIN_MSG = "用户未登录";
    private static final String INVALID_TOKEN_MSG = "无效的用户令牌";
    private static final String SYSTEM_ERROR_MSG = "系统异常，请稍后重试";

    private final IdentityVerifyService identityVerifyService;
    private final JwtUtil jwtUtil;

    @PostMapping("/verify")
    @Operation(
        summary = "提交实名认证", 
        description = "用户提交身份证号码和真实姓名进行实名认证，通过阿里云身份认证服务验证"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "认证请求提交成功",
            content = @Content(schema = @Schema(implementation = IdentityVerifyResponseDto.class))
        ),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "401", description = "用户未登录"),
        @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @SecurityRequirement(name = "Bearer Authentication")
    public Result<IdentityVerifyResponseDto> verifyIdentity(
            @Parameter(description = "实名认证请求参数", required = true)
            @Valid @RequestBody IdentityVerifyRequestDto request,
            HttpServletRequest httpRequest) {
        
        try {
            // 从请求头中获取JWT令牌
            String authHeader = httpRequest.getHeader(AUTHORIZATION_HEADER);
            if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
                return Result.error(401, USER_NOT_LOGIN_MSG);
            }

            String token = authHeader.substring(7);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                return Result.error(401, INVALID_TOKEN_MSG);
            }

            log.info("用户 {} 提交实名认证申请", userId);
            
            IdentityVerifyResponseDto response = identityVerifyService.verifyIdentity(request, userId);
            
            if (response.getPassed() != null && response.getPassed()) {
                return Result.success(response, "实名认证成功");
            } else {
                return Result.error(400, response.getResultMessage());
            }

        } catch (Exception e) {
            log.error("实名认证接口异常", e);
            return Result.error(500, SYSTEM_ERROR_MSG);
        }
    }

    @GetMapping("/status")
    @Operation(
        summary = "查询实名认证状态", 
        description = "查询当前用户的实名认证状态和相关信息"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "查询成功",
            content = @Content(schema = @Schema(implementation = IdentityVerifyResponseDto.class))
        ),
        @ApiResponse(responseCode = "401", description = "用户未登录"),
        @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @SecurityRequirement(name = "Bearer Authentication")
    public Result<IdentityVerifyResponseDto> getVerifyStatus(HttpServletRequest httpRequest) {
        
        try {
            // 从请求头中获取JWT令牌
            String authHeader = httpRequest.getHeader(AUTHORIZATION_HEADER);
            if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
                return Result.error(401, USER_NOT_LOGIN_MSG);
            }

            String token = authHeader.substring(7);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                return Result.error(401, INVALID_TOKEN_MSG);
            }

            IdentityVerifyResponseDto response = identityVerifyService.getUserVerifyInfo(userId);
            return Result.success(response);

        } catch (Exception e) {
            log.error("查询实名认证状态异常", e);
            return Result.error(500, SYSTEM_ERROR_MSG);
        }
    }

    @GetMapping("/check")
    @Operation(
        summary = "检查用户是否已实名认证", 
        description = "简单检查当前用户是否已完成实名认证，返回布尔值"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "401", description = "用户未登录"),
        @ApiResponse(responseCode = "500", description = "系统异常")
    })
    @SecurityRequirement(name = "Bearer Authentication")
    public Result<Boolean> checkVerifyStatus(HttpServletRequest httpRequest) {
        
        try {
            // 从请求头中获取JWT令牌
            String authHeader = httpRequest.getHeader(AUTHORIZATION_HEADER);
            if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
                return Result.error(401, USER_NOT_LOGIN_MSG);
            }

            String token = authHeader.substring(7);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                return Result.error(401, INVALID_TOKEN_MSG);
            }

            boolean isVerified = identityVerifyService.isUserVerified(userId);
            return Result.success(isVerified);

        } catch (Exception e) {
            log.error("检查实名认证状态异常", e);
            return Result.error(500, SYSTEM_ERROR_MSG);
        }
    }
}
