/*
 * 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.apache.paimon.utils;

import org.apache.paimon.catalog.CatalogContext;
import org.apache.paimon.fs.IsolatedDirectoryFileIO;
import org.apache.paimon.fs.Path;
import org.apache.paimon.fs.SeekableInputStream;
import org.apache.paimon.options.Options;
import org.apache.paimon.utils.UriReader.FileUriReader;
import org.apache.paimon.utils.UriReader.HttpUriReader;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.file.Files;

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

/** Test for {@link UriReaderFactory}. */
public class UriReaderFactoryTest {

    private final UriReaderFactory factory =
            new UriReaderFactory(CatalogContext.create(new Options()));

    @TempDir java.nio.file.Path tempPath;

    private HttpServer httpServer;
    private int httpPort;

    @BeforeEach
    public void setUpHttpServer() throws Exception {
        httpServer = HttpServer.create(new InetSocketAddress(0), 0);
        httpPort = httpServer.getAddress().getPort();
        httpServer.start();
    }

    @AfterEach
    public void tearDownHttpServer() {
        if (httpServer != null) {
            httpServer.stop(0);
        }
    }

    @Test
    public void testCreateHttpUriReader() {
        UriReader reader = factory.create("http://example.com/file.txt");
        assertThat(reader).isInstanceOf(HttpUriReader.class);
    }

    @Test
    public void testInvalidUriDoesNotLeakCredentials() {
        assertThatThrownBy(
                        () -> factory.create("https://alice:secret@host/bad path?sig=QUERY_SECRET"))
                .isInstanceOf(IllegalArgumentException.class)
                .hasNoCause()
                .satisfies(
                        e -> {
                            assertThat(String.valueOf(e)).doesNotContain("secret");
                            assertThat(String.valueOf(e)).doesNotContain("QUERY_SECRET");
                        });
    }

    @Test
    public void testInvalidUpperCaseHttpUriDoesNotFallBackToFileReader() {
        assertThatThrownBy(() -> factory.create("HTTPS://example.com/bad path"))
                .isInstanceOf(IllegalArgumentException.class);
    }

    @Test
    public void testCreateHttpsUriReader() {
        UriReader reader = factory.create("https://example.com/file.txt");
        assertThat(reader).isInstanceOf(HttpUriReader.class);
    }

    @Test
    public void testCreateFileUriReader() {
        UriReader reader = factory.create("file:///path/to/file.txt");
        assertThat(reader).isInstanceOf(FileUriReader.class);
    }

    @Test
    public void testReadFileUriWithUnescapedCharacters() throws Exception {
        java.nio.file.Path file = tempPath.resolve("\u4ed5\u5e9c\u516c\u9986 (2).jpg");
        Files.write(file, new byte[] {1, 2});
        String fileUri = "file://" + file.toAbsolutePath();

        UriReader reader = factory.create(fileUri);

        assertThat(reader).isInstanceOf(FileUriReader.class);
        try (SeekableInputStream inputStream = reader.newInputStream(fileUri)) {
            assertThat(inputStream.read()).isEqualTo(1);
            assertThat(inputStream.read()).isEqualTo(2);
        }
    }

    @Test
    public void testProvidedFileIOSurvivesSerialization() throws Exception {
        java.nio.file.Path file = tempPath.resolve("file.txt");
        Files.write(file, new byte[] {1, 2});

        Options options = new Options();
        options.set(IsolatedDirectoryFileIO.ROOT_DIR, new Path(tempPath.toUri()).toString());
        IsolatedDirectoryFileIO fileIO = new IsolatedDirectoryFileIO();
        fileIO.configure(CatalogContext.create(options));

        String fileUri = file.toUri().toString();
        UriReaderFactory originalFactory = UriReaderFactory.fromFileIO(fileIO);
        UriReader originalReader = originalFactory.create(fileUri);
        UriReaderFactory fileIOFactory = InstantiationUtil.clone(originalFactory);
        UriReader deserializedReader = fileIOFactory.create(fileUri);

        assertThat(deserializedReader).isNotSameAs(originalReader);
        try (SeekableInputStream inputStream = deserializedReader.newInputStream(fileUri)) {
            assertThat(inputStream.read()).isEqualTo(1);
            assertThat(inputStream.read()).isEqualTo(2);
        }
    }

    @Test
    public void testCreateUriReaderWithAuthority() {
        UriReader reader1 = factory.create("http://my_bucket1/path/to/file.txt");
        UriReader reader2 = factory.create("http://my_bucket2/path/to/file.txt");
        assertThat(reader1).isNotEqualTo(reader2);
    }

    @Test
    public void testCachedReadersWithSameSchemeAndAuthority() {
        UriReader reader1 = factory.create("http://my_bucket/path/to/file1.txt");
        UriReader reader2 = factory.create("http://my_bucket/path/to/file2.txt");
        assertThat(reader1).isSameAs(reader2);
    }

    @Test
    public void testCachedReadersWithNullAuthority() {
        UriReader reader1 = factory.create("file:///path/to/file1.txt");
        UriReader reader2 = factory.create("file:///path/to/file2.txt");
        assertThat(reader1).isSameAs(reader2);
    }

    @Test
    public void testCreateUriReaderWithLocalPath() {
        UriReader reader = factory.create("/local/path/to/file.txt");
        assertThat(reader).isInstanceOf(FileUriReader.class);
    }

    @Test
    public void testExistsUsesCachedFileUriReader() throws Exception {
        java.nio.file.Path file = tempPath.resolve("file.txt");
        Files.write(file, new byte[] {1});

        assertThat(factory.exists(file.toUri().toString())).isTrue();
        assertThat(factory.exists(tempPath.resolve("missing.txt").toUri().toString())).isFalse();
    }

    @Test
    public void testExistsReturnsFalseForMissingHttpResource() throws Exception {
        registerHttpHandler(
                "/missing.txt",
                exchange -> {
                    sendResponse(exchange, 404, new byte[0]);
                });

        assertThat(factory.exists(httpUrl("/missing.txt"))).isFalse();
    }

    @Test
    public void testExistsReturnsTrueForAvailableHttpResource() throws Exception {
        registerHttpHandler(
                "/ok.txt",
                exchange -> {
                    sendResponse(exchange, 200, "ok".getBytes());
                });

        assertThat(factory.exists(httpUrl("/ok.txt"))).isTrue();
    }

    @Test
    public void testReadersReinitializedAfterDeserialization() throws Exception {
        UriReaderFactory deserializedFactory = InstantiationUtil.clone(factory);
        UriReader reader1 = deserializedFactory.create("http://my_bucket/path/to/file1.txt");
        UriReader reader2 = deserializedFactory.create("http://my_bucket/path/to/file2.txt");
        assertThat(reader1).isSameAs(reader2);
    }

    private void registerHttpHandler(String path, com.sun.net.httpserver.HttpHandler handler) {
        httpServer.createContext(path, handler);
    }

    private String httpUrl(String path) {
        return "http://127.0.0.1:" + httpPort + path;
    }

    private static void sendResponse(HttpExchange exchange, int statusCode, byte[] body)
            throws IOException {
        boolean headRequest = "HEAD".equals(exchange.getRequestMethod());
        long responseLength = headRequest ? -1 : body.length;
        exchange.sendResponseHeaders(statusCode, responseLength);
        if (!headRequest && body.length > 0) {
            try (OutputStream outputStream = exchange.getResponseBody()) {
                outputStream.write(body);
            }
        } else {
            exchange.close();
        }
    }
}
