package org.qinan.safetyeval.start.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerControllerDeduplicateConfig {

    private static final String SPRINGFOX_SWAGGER_CONTROLLER = "swagger2ControllerWebMvc";
    private static final String JJB_SWAGGER_CONTROLLER = "swagger2ControllerWebMvc1";

    @Bean
    public static BeanDefinitionRegistryPostProcessor swaggerControllerDeduplicatePostProcessor() {
        return new BeanDefinitionRegistryPostProcessor() {
            @Override
            public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
                if (registry.containsBeanDefinition(SPRINGFOX_SWAGGER_CONTROLLER)
                        && registry.containsBeanDefinition(JJB_SWAGGER_CONTROLLER)) {
                    registry.removeBeanDefinition(SPRINGFOX_SWAGGER_CONTROLLER);
                }
            }

            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
                // No-op.
            }
        };
    }
}