package test05.controller;

import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import test05.pojo.Result;
import test05.pojo.User;
import test05.service.UserService;
import test05.utils.JwtUtils;

import java.util.Map;

@RestController
@RequestMapping("/userAction")
public class LoginController {
    private final UserService userService;
    @Autowired
    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/login")
    public Result login(String username, String password, HttpSession session) {
        if (session.getAttribute("user") != null) {
            @SuppressWarnings("unchecked") String loginName = ((Map<String, String>)(JwtUtils.parseJwt((String)session.getAttribute("user")).get("data"))).get("name");
            if (loginName.equals(username)) {
                return Result.success(session.getAttribute("user"));
            }
        }
        if (username==null || password==null) {
            return Result.error("login fail");
        }
        Result res = userService.login(new User(username, password));
        if (res.isSuccess()) {
            session.setAttribute("user", res.getData());
        }
        return res;
    }

    @RequestMapping("/logout")
    public Result logout(HttpSession session) {
        session.removeAttribute("user");
        return Result.success();
    }

}
