package com.emotion.controller;

import com.emotion.common.Result;
import com.emotion.dto.request.LoginRequest;
import com.emotion.dto.request.RegisterRequest;
import com.emotion.dto.request.RefreshTokenRequest;
import com.emotion.dto.request.ResetPasswordRequest;
import com.emotion.dto.response.ResetPasswordResponse;

import com.emotion.dto.response.AuthResponse;
import com.emotion.dto.response.CaptchaResponse;
import com.emotion.dto.response.SmsCodeResponse;
import com.emotion.dto.response.UserInfoResponse;
import com.emotion.service.AuthService;
import com.emotion.service.TokenService;
import com.emotion.util.UserContextUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 认证控制器
 *
 * @author huazhongmin
 * @date 2025-07-23
 */
@RestController
@RequestMapping("/auth")
@Tag(name = "认证管理", description = "用户注册、登录、验证码等认证相关接口")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private TokenService tokenService;

    /**
     * 用户登录（简化版：手机号+验证码，不存在则自动注册）
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "使用手机号和短信验证码登录，若用户不存在则自动注册")
    public Result<AuthResponse> login(@Valid @RequestBody LoginRequest request) {
        AuthResponse response = authService.login(request);
        return Result.success("登录成功", response);
    }

    /**
     * 用户注册（简化版：仅需手机号、密码和短信验证码）
     */
    @PostMapping(value = "/register")
    @Operation(summary = "用户注册", description = "使用手机号、密码和短信验证码进行注册")
    public Result<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
        AuthResponse response = authService.register(request);
        return Result.success("注册成功", response);
    }

    /**
     * 重置密码（手机号 + 验证码）
     */
    @PostMapping(value = "/resetPassword")
    @Operation(summary = "重置密码", description = "通过手机号和验证码重置密码，验证码本期固定为123456")
    public Result<ResetPasswordResponse> resetPassword(@Valid @RequestBody ResetPasswordRequest request) {
        ResetPasswordResponse response = authService.resetPassword(request);
        return Result.success("重置密码成功", response);
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/userInfo")
    public Result<UserInfoResponse> getCurrentUserInfo(HttpServletRequest request) {
        UserInfoResponse userInfo = tokenService.getUserInfoByToken(request);
        return Result.success(userInfo);
    }

    /**
     * 生成验证码（图形验证码，用于登录）
     */
    @GetMapping("/captcha")
    @Operation(summary = "获取图形验证码", description = "用于登录时的图形验证码")
    public Result<CaptchaResponse> generateCaptcha() {
        CaptchaResponse response = authService.generateCaptcha();
        return Result.success(response);
    }

    /**
     * 获取短信验证码（用于注册）
     */
    @GetMapping("/sms-code")
    @Operation(summary = "获取短信验证码", description = "用于注册时的短信验证码")
    public Result<SmsCodeResponse> getSmsCode(
            @Parameter(description = "手机号", required = true)
            @RequestParam String phone) {
        SmsCodeResponse response = authService.sendSmsCode(phone);
        return Result.success("验证码已发送", response);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        authService.logoutByToken(request);
        return Result.success();
    }

    /**
     * 刷新访问令牌
     */
    @PostMapping("/refreshToken")
    public Result<AuthResponse> refreshToken(@Valid @RequestBody RefreshTokenRequest request) {
        AuthResponse response = authService.refreshToken(request.getRefreshToken());
        return Result.success("令牌刷新成功", response);
    }

    /**
     * 验证访问令牌
     */
    @GetMapping("/validateToken")
    public Result<Boolean> validateToken(HttpServletRequest request) {
        boolean isValid = authService.validateToken(request);
        return Result.success(isValid);
    }

    /**
     * 获取用户名（通过令牌）
     */
    @GetMapping("/username")
    public Result<String> getUsernameFromToken(HttpServletRequest request) {
        String username = tokenService.getUsernameByToken(request);
        return Result.success(username);
    }

    /**
     * 检查账号是否存在
     */
    @GetMapping("/checkAccount")
    public Result<Boolean> checkAccount(@RequestParam String account) {
        boolean exists = authService.existsByAccount(account);
        return Result.success(exists);
    }

    /**
     * 检查邮箱是否存在
     */
    @GetMapping("/checkEmail")
    public Result<Boolean> checkEmail(@RequestParam String email) {
        boolean exists = authService.existsByEmail(email);
        return Result.success(exists);
    }

    /**
     * 检查手机号是否存在
     */
    @GetMapping("/checkPhone")
    public Result<Boolean> checkPhone(@RequestParam String phone) {
        boolean exists = authService.existsByPhone(phone);
        return Result.success(exists);
    }
}