package com.njzscloud.common.security.module.password;

import com.njzscloud.common.core.ex.ExceptionMsg;
import com.njzscloud.common.core.jackson.Jackson;
import com.njzscloud.common.security.ex.UserLoginException;
import com.njzscloud.common.security.support.LoginForm;
import com.njzscloud.common.security.support.LoginPreparer;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;

import static com.njzscloud.common.security.contant.Constants.LOGIN_URL;

/**
 * 账号密码登录，登录参数处理器
 */
@Slf4j
public class PasswordLoginPreparer implements LoginPreparer {
    private static final PathPatternRequestMatcher matcher = PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, LOGIN_URL);

    /**
     * 创建登录参数
     *
     * @param request 请求信息
     * @return 登录参数 {@link PasswordLoginForm}
     */
    @Override
    public LoginForm createLoginForm(HttpServletRequest request) {
        try (ServletInputStream inputStream = request.getInputStream()) {
            LoginForm loginForm = Jackson.toBean(inputStream, PasswordLoginForm.class);
            log.info("账号密码登录表单：{}", Jackson.toJsonStr(loginForm));
            return loginForm;
        } catch (Exception e) {
            throw new UserLoginException(e, ExceptionMsg.SYS_ERR_MSG, "登录表单解析失败");
        }
    }

    /**
     * 是否支持当前登录方式
     *
     * @param request 请求信息
     * @return 当请求方式为 POST 且路径为 /login 时返回 true
     */
    @Override
    public boolean support(HttpServletRequest request) {
        return matcher.matches(request);
    }

}
