package me.qwq.doghouse.config;

import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import lombok.extern.slf4j.Slf4j;
import me.qwq.doghouse.annotation.ConfigInfo;

/**
 * 实现自动化注册 Config
 */
@Slf4j
public class ConfigAutoRegistrar implements BeanDefinitionRegistryPostProcessor {

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter(new AnnotationTypeFilter(ConfigInfo.class));
        
        scanner.findCandidateComponents("me.qwq.doghouse.entity.config").forEach(beanDefinition -> {
            String className = beanDefinition.getBeanClassName();
            try {
                Class<?> clazz = Class.forName(className);
                String beanName = clazz.getSimpleName().substring(0, 1).toLowerCase() + clazz.getSimpleName().substring(1);
                BeanDefinitionBuilder factoryBean = BeanDefinitionBuilder
                    .genericBeanDefinition(ConfigServiceFactoryBean.class)
                    .addConstructorArgValue(clazz);
                registry.registerBeanDefinition(beanName, factoryBean.getBeanDefinition());
                log.info("Config part {} registered", beanName);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException("Failed to load class: " + className, e);
            }
        });
    }
}