package com.cameleer.server.app.http;

import com.cameleer.server.core.http.OutboundHttpProperties;
import com.cameleer.server.core.http.OutboundHttpRequestContext;
import com.cameleer.server.core.http.TrustMode;
import org.junit.jupiter.api.Test;

import javax.net.ssl.SSLContext;
import java.nio.file.Path;
import java.time.Duration;
import java.util.List;

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

class SslContextBuilderTest {
    private final OutboundHttpProperties systemProps =
            new OutboundHttpProperties(false, List.of(), Duration.ofMillis(2000), Duration.ofMillis(5000),
                                        null, null, null);
    private final SslContextBuilder builder = new SslContextBuilder();

    @Test
    void systemDefaultUsesJdkTrustStore() throws Exception {
        SSLContext ctx = builder.build(systemProps, OutboundHttpRequestContext.systemDefault());
        assertThat(ctx).isNotNull();
        assertThat(ctx.getProtocol()).isEqualTo("TLS");
    }

    @Test
    void trustAllSkipsValidation() throws Exception {
        SSLContext ctx = builder.build(systemProps,
                new OutboundHttpRequestContext(TrustMode.TRUST_ALL, List.of(), null, null));
        assertThat(ctx).isNotNull();
    }

    @Test
    void trustPathsLoadsPemFile() throws Exception {
        Path pem = Path.of(getClass().getClassLoader().getResource("test-ca.pem").toURI());
        assertThat(pem).exists();
        SSLContext ctx = builder.build(systemProps,
                new OutboundHttpRequestContext(TrustMode.TRUST_PATHS, List.of(pem.toString()), null, null));
        assertThat(ctx).isNotNull();
    }

    @Test
    void trustPathsMissingFileThrows() {
        assertThatThrownBy(() -> builder.build(systemProps,
                new OutboundHttpRequestContext(TrustMode.TRUST_PATHS, List.of("/no/such/file.pem"), null, null)))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessageContaining("CA file not found");
    }

    @Test
    void systemTrustAllShortCircuitsEvenWithSystemDefaultContext() throws Exception {
        OutboundHttpProperties trustAllProps = new OutboundHttpProperties(
                true, List.of(), Duration.ofMillis(2000), Duration.ofMillis(5000),
                null, null, null);
        SSLContext ctx = builder.build(trustAllProps, OutboundHttpRequestContext.systemDefault());
        assertThat(ctx).isNotNull();
        assertThat(ctx.getProtocol()).isEqualTo("TLS");
    }
}
