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

import com.njzscloud.common.core.ex.ExceptionMsg;
import com.njzscloud.common.core.jackson.Jackson;
import com.njzscloud.common.security.contant.Constants;
import com.njzscloud.common.security.ex.UserLoginException;
import com.njzscloud.common.security.module.password.PasswordLoginForm;
import com.njzscloud.common.security.support.LoginForm;
import com.njzscloud.common.security.support.LoginPreparer;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;

/**
 * 验证码登录，登录参数处理器
 */
public class CodeLoginPreparer implements LoginPreparer {
    private static final PathPatternRequestMatcher matcher = PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, Constants.LOGIN_CODE_URL);

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

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

}
