package org.raddatz.familienarchiv.config;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.web.server.autoconfigure.ServerProperties.ForwardHeadersStrategy;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.ClassPathResource;

import java.util.Properties;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Binds {@code server.forward-headers-strategy} from {@code application.yaml} into
 * Spring Boot's typed {@link ForwardHeadersStrategy} enum. The binder rejects any
 * value that is not a valid enum constant ({@code BindException}), so a typo
 * ({@code "nativ"}, {@code "Native"}, {@code "framework "}) or a future Spring
 * rename of the property fails the test, not silently degrades to {@code NONE}.
 *
 * <p>No Spring context, no embedded server, no Testcontainers — this is the
 * cheapest test that pins the contract "Caddy's X-Forwarded-Proto is trusted".
 */
class ForwardHeadersConfigurationTest {

    @Test
    void forward_headers_strategy_binds_to_NATIVE() {
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("application.yaml"));
        Properties props = yaml.getObject();
        assertThat(props).as("application.yaml must be on the classpath").isNotNull();

        Binder binder = new Binder(ConfigurationPropertySources.from(
            new PropertiesPropertySource("application", props)));

        ForwardHeadersStrategy strategy = binder
            .bind("server.forward-headers-strategy", ForwardHeadersStrategy.class)
            .orElseThrow(() -> new AssertionError(
                "server.forward-headers-strategy is missing from application.yaml"));

        assertThat(strategy)
            .as("Spring must trust X-Forwarded-Proto from Caddy so that "
                + "request.getScheme(), redirect URLs, and the Spring Session "
                + "'Secure' cookie reflect the original https client request.")
            .isEqualTo(ForwardHeadersStrategy.NATIVE);
    }
}
