package com.qaup.collision.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.util.Properties;

/**
 * Custom PropertySourceFactory to allow loading properties from YAML files
 * using the @PropertySource annotation.
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    @NonNull
    public PropertySource<?> createPropertySource(@Nullable String name, @NonNull EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());

        Properties properties = factory.getObject();

        // Ensure properties is not null before creating the PropertySource
        if (properties == null) {
            throw new IllegalStateException("Failed to load YAML properties from resource: " + resource.getResource());
        }

        // Use the filename as the name of the PropertySource if 'name' is null
        String sourceName = (name != null) ? name : resource.getResource().getFilename();
        if (sourceName == null) {
             // Fallback if filename is also null (should be rare)
            sourceName = "yamlPropertySource";
        }
        
        return new PropertiesPropertySource(sourceName, properties);
    }
} 