package com.hz.pm.api.user.security.auth.mh;

import com.hz.pm.api.external.MhAuthClient;
import com.hz.pm.api.external.model.dto.MhRetDTO;
import com.hz.pm.api.user.security.model.WebRequestDetails;
import com.ningdatech.basic.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * AgentAuthFilter
 * </p>
 *
 * @author WendyYang
 * @since 11:20 2023/12/26
 */
public class MhAuthFilter extends AbstractAuthenticationProcessingFilter {

    private static final String AUTH_CODE = "code";

    private final MhAuthClient authClient;

    // ~ Constructors
    // ===================================================================================================

    public MhAuthFilter(String processingUrl, MhAuthClient authClient) {
        super(new AntPathRequestMatcher(processingUrl, HttpMethod.POST.name()));
        this.authClient = authClient;
    }

    // ========================================================================================================

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
            throws AuthenticationException {
        if (!request.getMethod().equals(HttpMethod.POST.name())) {
            throw new AuthenticationServiceException("请求方法错误");
        }
        String authCode = request.getParameter(AUTH_CODE);
        if (StringUtils.isBlank(authCode)) {
            throw new BadCredentialsException("授权码不能为空");
        }
        // 获取临时授权码对应的mhUserId或者openId
        MhRetDTO<String> mhRet = authClient.getMhUserIdByAuthCode(authCode);
        if (!mhRet.isOk()) {
            throw BizException.wrap("登录失败，授权码无效");
        }
        String mhUserIdOrOpenId = mhRet.getData();
        try {
            MhAuthToken authRequest = new MhAuthToken(mhUserIdOrOpenId, mhUserIdOrOpenId);
            authRequest.setDetails(new WebRequestDetails(request));
            return this.getAuthenticationManager().authenticate(authRequest);
        } catch (BizException e) {
            throw new BadCredentialsException(e.getMessage());
        } catch (Exception e) {
            throw new InternalAuthenticationServiceException("授权失败：", e);
        }
    }

}
