package org.qinan.safetyeval.start.config;

import com.jjb.saas.framework.auth.properties.ServerProperties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServerPropertiesPrimaryConfig {

    @Bean
    public static BeanFactoryPostProcessor serverPropertiesPrimaryPostProcessor() {
        return new BeanFactoryPostProcessor() {
            @Override
            public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
                String[] names = beanFactory.getBeanNamesForType(ServerProperties.class, true, false);
                if (names.length <= 1) {
                    return;
                }
                String primaryName = names[0];
                for (String name : names) {
                    if (name.startsWith("sdk.server-")) {
                        primaryName = name;
                        break;
                    }
                }
                for (String name : names) {
                    BeanDefinition definition = beanFactory.getBeanDefinition(name);
                    definition.setPrimary(name.equals(primaryName));
                }
            }
        };
    }
}