package com.eactive.eai.authserver.config;

import javax.servlet.Filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenEndpointFilter;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.stereotype.Component;

import com.eactive.eai.authserver.dao.TokenIssuanceLogDAO;

@Component
public class OAuth2FilterCustomizer implements ApplicationListener<ContextRefreshedEvent> {

    private boolean initialized = false;
    
    @Autowired
	private TokenIssuanceLogDAO tokenIssuanceLogDAO;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (initialized) return;
        
        Filter springSecurityFilterChain = event.getApplicationContext()
                .getBean("springSecurityFilterChain", Filter.class);
        
        FilterChainProxy filterChainProxy = (FilterChainProxy) springSecurityFilterChain;
        
        filterChainProxy.getFilterChains().stream()
            .flatMap(chain -> chain.getFilters().stream())
            .filter(filter -> filter instanceof ClientCredentialsTokenEndpointFilter)
            .forEach(filter -> ((ClientCredentialsTokenEndpointFilter) filter)
                .setAuthenticationEntryPoint(new CustomOAuth2AuthenticationEntryPoint(tokenIssuanceLogDAO)));
        
        initialized = true;
    }
}