package com.simuwang.manage.api;

import cn.hutool.core.map.MapUtil;
import com.simuwang.base.config.DaqProperties;
import com.simuwang.manage.dto.LoginUser;
import com.simuwang.shiro.core.ShiroToken;
import com.simuwang.shiro.core.jwt.JwtContext;
import com.smppw.common.pojo.ResultVo;
import com.smppw.common.pojo.enums.status.ResultCode;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/v1")
public class LoginController {
    private final JwtContext jwtContext;
    private final DaqProperties properties;

    public LoginController(JwtContext jwtContext, DaqProperties properties) {
        this.jwtContext = jwtContext;
        this.properties = properties;
    }

    @GetMapping("rsa-key")
    public Map<String, Object> getRsaKey() {
        return MapUtil.<String, Object>builder("rsaKey", this.properties.getSecurityRsa().getPublicKey()).build();
    }

    @PostMapping("login")
    public ResultVo<String> login(@RequestBody LoginUser loginUser, HttpServletResponse response) {
        ShiroToken shiroToken = new ShiroToken(loginUser.getUsername(), loginUser.getPassword());
        Subject subject = SecurityUtils.getSubject();
        subject.login(shiroToken);

        String token = jwtContext.generateToken(loginUser.getUsername());
        this.jwtContext.setUserCache(token);
        response.setHeader(JwtContext.HEADER, token);
        response.setHeader("Access-control-Expost-Headers", JwtContext.HEADER);
        return ResultVo.ok(ResultCode.SUCCESS.getCode(), "登录成功", token);
    }

    @RequiresAuthentication
    @PostMapping("/logout")
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        this.jwtContext.cleanUserCache(subject.getPrincipal().toString());
        subject.logout();
    }

    @RequiresPermissions("RS:TEST")
    @GetMapping("/user-info")
    public Object getUserInfo() {
        return SecurityUtils.getSubject().getPrincipal();
    }
}
