package com.xingxi.api.configuration.security;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
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.stream.Stream;

@Slf4j
@RequiredArgsConstructor
class JwtAuthenticationFilter extends OncePerRequestFilter {
    private final JwtAuthenticationConverter authenticationConverter = new JwtAuthenticationConverter();
    private final JwtAuthenticationManager jwtAuthenticationManager;
    final String[] ignoreUrls = { "/api/store/order/wxpay/callback" };

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.debug("JwtAuthenticationFilter.doFilterInternal()...");

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String servletPath = request.getServletPath();

        boolean exists = Stream.of(ignoreUrls).anyMatch(s -> servletPath.contains(s));
        if (exists) {
            filterChain.doFilter(httpRequest, response);
            return;
        }

        try {
            UsernamePasswordAuthenticationToken authRequest = this.authenticationConverter.convert(request);
            if (authRequest != null) {
                Authentication authResult = jwtAuthenticationManager.authenticate(authRequest);
                SecurityContextHolder.getContext().setAuthentication(authResult);
            }
        } catch (Exception e){
//            e.printStackTrace();
            log.error(e.getMessage());
            SecurityContextHolder.clearContext();
        }

        filterChain.doFilter(request, response);
    }

}
