package com.luojia_channel.modules.user.controller;

import com.luojia_channel.common.domain.Result;
import com.luojia_channel.common.domain.UserDTO;
import com.luojia_channel.common.utils.RedisUtil;
import com.luojia_channel.modules.user.utils.CaptchaUtils;
import com.luojia_channel.modules.user.dto.UserLoginDTO;
import com.luojia_channel.modules.user.dto.UserRegisterDTO;
import com.luojia_channel.modules.user.service.UserLoginService;
import com.luojia_channel.modules.user.vo.UserInfoVO;
import io.swagger.v3.oas.annotations.Hidden;
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.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Tag(name = "用户管理", description = "用户登陆注册相关接口")
public class UserLoginController {
    private final UserLoginService userLoginService;
    private final RedisUtil redisUtil;
    
    @PostMapping("/login")
    @Operation(
            summary = "用户登录",
            description = "支持用户名/手机号/邮箱登录",
            tags = {"用户管理"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "登录成功",content = @Content(schema = @Schema(implementation = UserInfoVO.class))),
            @ApiResponse(responseCode = "500", description = "登录失败，用户名或密码错误")
    })
    public Result<UserInfoVO> login(@RequestBody UserLoginDTO userLoginDTO){
        return Result.success(userLoginService.login(userLoginDTO));
    }

    @PostMapping("/check-login")
    @Operation(
            summary = "检查用户登录状态",
            description = "通过accessToken和refreshToken验证用户登录状态",
            tags = {"用户管理"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "验证成功"),
            @ApiResponse(responseCode = "500", description = "验证失败，token无效或已过期")
    })
    public Result<UserDTO> checkLogin(@RequestHeader(value = "Authorization", required = false) String accessToken,
                                     @RequestHeader(value = "X-Refresh-Token", required = false) String refreshToken) {
        if (accessToken != null && accessToken.startsWith("Bearer ")) {
            accessToken = accessToken.substring(7);
        }
        return Result.success(userLoginService.checkLogin(accessToken, refreshToken));
    }

    @PostMapping("/register")
    @Operation(
            summary = "用户注册",
            description = "支持用户名/手机号/邮箱注册",
            tags = {"用户管理"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "注册成功"),
            @ApiResponse(responseCode = "500", description = "注册失败，请稍后重试")
    })
    public Result<UserDTO> register(@RequestBody UserRegisterDTO userRegisterDTO){
        return Result.success(userLoginService.register(userRegisterDTO));
    }

    @PostMapping("/logout")
    @Operation(
            summary = "用户登出",
            tags = {"用户管理"}
    )
    public Result<Void> logout(HttpServletRequest request){
        userLoginService.logout(request);
        return Result.success();
    }

    @Hidden
    @PostMapping("/hello")
    @Operation(summary = "测试接口")
    public Result<String> hello(){
        return Result.success("hello");
    }


    /**
     * 生成验证码图片
     * @param request
     * @param res
     * @throws IOException
     */
    @GetMapping("/captcha")
    @Operation(
            summary = "生成验证码图片",
            description = "生成图形验证码并设置Cookie存储captchaKey",
            tags = {"用户管理"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "验证码生成成功"),
            @ApiResponse(responseCode = "500", description = "验证码生成失败")
    })
    public void generateCaptcha(HttpServletRequest request,
                                HttpServletResponse res) throws IOException {

        CaptchaUtils captcha = new CaptchaUtils();
        BufferedImage image = captcha.getImage();
        String text = captcha.getText();

        String captchaKey = UUID.randomUUID().toString();
        redisUtil.set("captcha:" + captchaKey, text, 60, TimeUnit.SECONDS);

        Cookie cookie = new Cookie("captchaKey", captchaKey);
        cookie.setPath("/");
        res.addCookie(cookie);

        CaptchaUtils.output(image,res.getOutputStream());
    }

    /**
     * 验证验证码
     * @param session
     * @param params
     * @return
     */
    @PostMapping("/verify-captcha")
    @Operation(
            summary = "验证图形验证码",
            description = "验证用户输入的图形验证码是否正确",
            tags = {"用户管理"}
    )
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "验证码验证成功"),
            @ApiResponse(responseCode = "500", description = "验证码已失效或验证码错误")
    })
    public Result verifyCaptcha(@RequestBody Map<String, String> params, 
                               @CookieValue(value = "captchaKey", required = false) String captchaKey, 
                               HttpSession session) {
        String captcha = params.get("captcha");

        if (captchaKey == null) {
            return Result.fail(500, "验证码已失效，请重新获取");
        }

        String redisKey = "captcha:" + captchaKey;
        String correctCaptcha = redisUtil.get(redisKey, String.class);
        if (correctCaptcha == null) {
            return Result.fail(500, "验证码已过期，请重新获取");
        }

        if (captcha.equalsIgnoreCase(correctCaptcha)) {
            redisUtil.delete(redisKey);
            return Result.success();
        } else {
            return Result.fail(500, "图形验证码错误");
        }
    }
}
