package com.bicloud.controller;


import com.bicloud.common.result.Result;
import com.bicloud.common.utils.JwtUtils;
import com.bicloud.pojo.dto.LoginDto;
import com.bicloud.pojo.dto.RegisterDto;
import com.bicloud.pojo.vo.LoginVo;
import com.bicloud.pojo.vo.UserInfoVo;
import com.bicloud.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/user")
@Tag(name = "用户管理")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 发送手机验证码
     */
    @PostMapping("/code")
    @Operation(summary = "发送验证码")
    public Result sendCode(@RequestParam("mobile") String mobile, HttpSession session, HttpServletRequest request) {
        // 发送短信验证码并保存验证码
        return userService.sendCode(mobile, session, request);
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    @Operation(summary = "用户注册")
    public Result register(@Valid @RequestBody RegisterDto registerDto) {
        return userService.register(registerDto);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<LoginVo> login(@Valid @RequestBody LoginDto loginDto) {
        LoginVo loginVo = userService.login(loginDto);
        return Result.success(loginVo);
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refresh-token")
    @Operation(summary = "刷新Token")
    public Result<String> refreshToken(@RequestParam("refreshToken") String refreshToken) {
        String newAccessToken = userService.refreshToken(refreshToken);
        return Result.success(newAccessToken);
    }

    /**
     * 用户登出
     */
    @PostMapping("/logout")
    @Operation(summary = "用户登出")
    public Result logout(HttpServletRequest request) {
        String token = jwtUtils.extractToken(request);
        userService.logout(token);
        return Result.success("登出成功！");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    @Operation(summary = "获取当前用户信息")
    public Result<UserInfoVo> getUserInfo() {
        UserInfoVo userInfo = userService.getCurrentUserInfo();
        return Result.success(userInfo);
    }

}
