package com.sunyard.chsm.auth;


import com.sunyard.chsm.model.R;
import com.sunyard.chsm.service.AppLoginService;
import com.sunyard.chsm.utils.JsonUtils;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;

import static com.sunyard.chsm.constant.SecurityConstant.ATTRIBUTE_APP_USER;

/**
 * @author liulu
 * @version V1.0
 * @since 2023/8/4
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AppTokenFilter extends OncePerRequestFilter {

    public static final Collection<String> WHITE_URL = Arrays.asList(
            "/appUser/getAppToken",
            "/appUser/getAppTokenTest"
    );

    private final AppLoginService appLoginService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if (WHITE_URL.contains(requestURI)) {
            filterChain.doFilter(request, response);
            return;
        }

        String tokenValue = extractToken(request);
        if (ObjectUtils.isEmpty(tokenValue)) {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getOutputStream().write(JsonUtils.toJsonBytes(R.error("请先获取token后再访问")));
            return;
        }

        try {
            AppUser user = appLoginService.verifyToken(tokenValue);
            request.setAttribute(ATTRIBUTE_APP_USER, user);
            filterChain.doFilter(request, response);
        } catch (ExpiredJwtException ex) {
            log.warn("token已过期: {}", requestURI);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getOutputStream().write(JsonUtils.toJsonBytes(R.error("token已过期")));
        } catch (JwtException ex) {
            log.warn("token格式错误: {}", requestURI);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getOutputStream().write(JsonUtils.toJsonBytes(R.error("token格式错误")));
        } catch (Exception ex) {
            log.error("系统异常: {}", requestURI, ex);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.getOutputStream().write(JsonUtils.toJsonBytes(R.error("系统异常")));
        }

    }

    protected String extractToken(HttpServletRequest request) {
        // first check the header...
        String token = extractHeaderToken(request);

        // bearer type allows a request parameter as well
        if (token == null) {
            logger.debug("Token not found in headers. Trying request parameters.");
            token = request.getParameter("access_token");
            if (token == null) {
                logger.debug("Token not found in request parameters.  Not an OAuth2 request.");
            }
        }
        return token;
    }

    private static final String BEARER_TYPE = "Bearer";

    private String extractHeaderToken(HttpServletRequest request) {
        Enumeration<String> headers = request.getHeaders("Authorization");
        while (headers.hasMoreElements()) { // typically there is only one (most servers enforce that)
            String value = headers.nextElement();
            if (value.toLowerCase().startsWith(BEARER_TYPE.toLowerCase())) {
                String authHeaderValue = value.substring(BEARER_TYPE.length()).trim();
                int commaIndex = authHeaderValue.indexOf(',');
                if (commaIndex > 0) {
                    authHeaderValue = authHeaderValue.substring(0, commaIndex);
                }
                return authHeaderValue;
            }
        }

        return null;
    }

}
