/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.eclipse.aether.transport.jdk;

import java.net.ConnectException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Version;
import java.util.stream.Stream;

import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.internal.impl.DefaultPathProcessor;
import org.eclipse.aether.internal.test.util.TestUtils;
import org.eclipse.aether.internal.test.util.http.HttpTransporterTest;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.spi.connector.transport.PeekTask;
import org.eclipse.aether.spi.connector.transport.Transporter;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledForJreRange;
import org.junit.jupiter.api.condition.JRE;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

/**
 * JDK Transporter UT.
 * Related: <a href="https://dev.to/kdrakon/httpclient-can-t-connect-to-a-tls-proxy-118a">No TLS proxy supported</a>.
 */
class JdkTransporterTest extends HttpTransporterTest {

    static {
        // uncomment to enable http client logging
        // https://docs.oracle.com/en/java/javase/21/docs/api/java.net.http/module-summary.html#jdk.httpclient.HttpClient.log
        // System.setProperty("jdk.httpclient.HttpClient.log", "all");
        // even more fine-grained logging
        // System.setProperty("jdk.internal.httpclient.debug", "true");
    }

    private boolean isBetweenJava17and21() {
        JRE currentJre = JRE.currentJre();
        return currentJre.compareTo(JRE.JAVA_17) >= 0 && currentJre.compareTo(JRE.JAVA_21) <= 0;
    }

    @Override
    protected boolean supportsPreemptiveAuth() {
        // due to JDK-8326949 (https://bugs.openjdk.org/browse/JDK-8326949)
        return !isBetweenJava17and21();
    }

    @Override
    protected boolean supportsHttp3() {
        JRE currentJre = JRE.currentJre();
        return currentJre.compareTo(JRE.JAVA_26) >= 0;
    }

    @Override
    protected Stream<String> supportedCompressionAlgorithms() {
        return Stream.of("gzip", "deflate");
    }

    @Override
    protected boolean exposeContentCodingInTransportProperties() {
        // see https://issues.apache.org/jira/browse/HTTPCORE-792
        return false;
    }

    @Override
    @Disabled
    @Test
    protected void testPut_SSL() throws Exception {
        // fails due to 500 status being returned by Jetty
        // (https://github.com/jetty/jetty.project/issues/13157#issuecomment-4980954802).
    }

    @Override
    @Disabled
    @Test
    protected void testAuthSchemeReuse() {}

    @Override
    @Disabled
    @Test
    protected void testPut_ProxyUnauthenticated() {}

    @Override
    @Disabled
    @Test
    protected void testPut_Unauthenticated() {}

    @Override
    @Disabled
    @Test
    protected void testPut_Authenticated_ExpectContinueRejected_ExplicitlyConfiguredHeader() {}

    @Override
    @Test
    @EnabledForJreRange(max = JRE.JAVA_25)
    protected void testRetryHandler_defaultCount_negative() throws Exception {
        // internally JDK client uses its own retry mechanism with
        // 2 attempts for ConnectionExpiredException (prior Java 26)
        // afterwards it uses 5 (default for
        // system property "jdk.httpclient.redirects.retrylimit") attempts,
        // limit the internal retry count to 1 has global effect and is too late here anyway therefore we skip this test
        // for Java 26+.
        // Compare with https://github.com/mizosoft/methanol/issues/174
        httpServer.setConnectionsToClose(8);
        try {
            transporter.peek(new PeekTask(URI.create("repo/file.txt")));
            fail("Expected error");
        } catch (Exception expected) {
        }
    }

    public JdkTransporterTest() {
        super(() -> new JdkTransporterFactory(standardChecksumExtractor(), new DefaultPathProcessor()));
    }

    @Test
    void enhanceConnectExceptionMessages() {
        String uri = "https://localhost:12345/";
        RemoteRepository remoteRepository = new RemoteRepository.Builder("central", "default", uri).build();
        JdkTransporterFactory factory = new JdkTransporterFactory(s -> null, new DefaultPathProcessor());

        try (Transporter transporter = factory.newInstance(TestUtils.newSession(), remoteRepository)) {
            transporter.peek(new PeekTask(URI.create("repo/file.txt")));
            fail("This should throw");
        } catch (ConnectException e) {
            assertTrue(e.getMessage().contains("Connection to " + uri + " refused"), e.getMessage());
        } catch (Exception e) {
            fail("We expect ConnectException");
        }
    }

    @Test
    void testGetBasicAuthValue() {
        assertEquals(
                "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
                JdkTransporter.getBasicAuthValue("Aladdin", "open sesame".toCharArray()));
    }

    @Test
    void testMaximumHttpVersionAtRuntime() throws Exception {
        RepositorySystemSession session = TestUtils.newSession();
        RemoteRepository remoteRepository =
                new RemoteRepository.Builder("central", "default", "https://repo.maven.apache.org/maven2/").build();
        JdkTransporterFactory factory = new JdkTransporterFactory(s -> null, new DefaultPathProcessor());

        try (Transporter transporter = factory.newInstance(session, remoteRepository)) {
            JdkTransporter jdkTransporter = (JdkTransporter) transporter;
            HttpClient.Version[] versions = HttpClient.Version.values();
            HttpClient.Version maximumSupported = versions[versions.length - 1];
            assertEquals(maximumSupported, jdkTransporter.getMaximumSupportedHttpVersion());
            // default should be returned which is HTTP_2 for all JRE versions
            assertEquals(Version.HTTP_2, jdkTransporter.getHttpVersion(session, remoteRepository));
        }
    }
}
