package top.awinx.stu01.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import top.awinx.stu01.common.Result;
import top.awinx.stu01.config.JwtConfig;
import top.awinx.stu01.dto.LoginRequest;
import top.awinx.stu01.entity.SysUser;
import top.awinx.stu01.service.SysUserService;
import top.awinx.stu01.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import top.awinx.stu01.exception.BusinessException;

/**
 * 登录接口Controller
 */
@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private JwtConfig jwtConfig;

    /**
     * 登录接口（POST请求，接收JSON参数）
     * @param loginRequest JSON格式的登录参数
     * @return 统一返回结果
     */
    @PostMapping("")
    public Result<Object> login(@Valid @RequestBody LoginRequest loginRequest) {
        // 提取账号密码
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();

        // 调用Service校验账号密码
        SysUser sysUser = sysUserService.loginCheck(username, password);

        // 校验失败
        if (sysUser == null) {
            // throw new BusinessException("账号或密码错误");
            return Result.error("账号或密码错误");
        }

        // 生成JWT令牌
        String token = jwtUtil.generateToken(sysUser);

        // 组装返回数据（token+基础用户信息）
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        resultMap.put("user", sysUser);

        // 校验成功
        return Result.success("登录成功", resultMap);
    }

    /**
     * 登陆令牌刷新接口（GET请求，无参数）
     * @return 统一返回结果
     */
    @GetMapping("/refresh")
    public Result<Object> refresh(HttpServletRequest request) {
        String oldToken = request.getHeader(jwtConfig.getHeader());
        if (oldToken != null && oldToken.startsWith(jwtConfig.getPrefix())){
            oldToken = oldToken.substring(jwtConfig.getPrefix().length());
            oldToken = oldToken.trim();
        }
        if (oldToken == null || !jwtUtil.validateToken(oldToken)) {
            throw new BusinessException("请先登录或token已过期");
        }
        SysUser sysUser = jwtUtil.getUserFromToken(oldToken);
        String newToken = jwtUtil.generateToken(sysUser);
        return Result.success("刷新成功", newToken);
    }
}
