/*
 * 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.data;

import org.apache.paimon.fs.ByteArraySeekableStream;
import org.apache.paimon.fs.FileIO;
import org.apache.paimon.fs.Path;
import org.apache.paimon.fs.local.LocalFileIO;
import org.apache.paimon.utils.UriReader;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

/** Tests for {@link Blob}. */
public class BlobTest {

    @TempDir java.nio.file.Path tempPath;

    private String file;

    @BeforeEach
    void beforeEach() throws IOException {
        file = new File(tempPath.toString(), "test.txt").getAbsolutePath();
        Files.write(Paths.get(file), "test data".getBytes());
    }

    @Test
    public void testFromData() {
        byte[] testData = "test data".getBytes();
        Blob blob = Blob.fromData(testData);
        assertThat(blob).isInstanceOf(BlobData.class);
        assertThat(blob.toData()).isEqualTo(testData);
    }

    @Test
    public void testFromLocal() {
        Blob blob = Blob.fromLocal(file);
        assertThat(blob).isInstanceOf(BlobRef.class);
        assertThat(blob.toData()).isEqualTo("test data".getBytes());
    }

    @Test
    public void testFromFile() {
        Blob blob = Blob.fromFile(LocalFileIO.create(), file, 0, 4);
        assertThat(blob).isInstanceOf(BlobRef.class);
        assertThat(blob.toData()).isEqualTo("test".getBytes());
    }

    @Test
    public void testFromPath() {
        Blob blob = Blob.fromFile(LocalFileIO.create(), file);
        assertThat(blob).isInstanceOf(BlobRef.class);
        assertThat(blob.toData()).isEqualTo("test data".getBytes());
    }

    @Test
    public void testFromHttp() {
        String uri = "http://example.com/file.txt";
        Blob blob = Blob.fromHttp(uri);
        assertThat(blob).isInstanceOf(BlobRef.class);
    }

    @Test
    public void testToPresignedUrlDelegatesDescriptor() throws IOException {
        BlobDescriptor descriptor =
                new BlobDescriptor("oss://bucket/table/bucket-0/data.blob", 2, 4);
        Blob blob = Blob.fromDescriptor(mock(UriReader.class), descriptor);
        FileIO fileIO = mock(FileIO.class);
        Path tableRoot = new Path("oss://bucket/table");
        Duration validity = Duration.ofHours(1);
        when(fileIO.createBlobPresignedUrl(tableRoot, descriptor, validity))
                .thenReturn("https://example");

        assertThat(blob.toPresignedUrl(fileIO, tableRoot, validity)).isEqualTo("https://example");
        verify(fileIO).createBlobPresignedUrl(tableRoot, descriptor, validity);
    }

    @Test
    public void testInlineBlobCannotCreatePresignedUrl() {
        FileIO fileIO = mock(FileIO.class);

        assertThatThrownBy(
                        () ->
                                Blob.fromData(new byte[] {1})
                                        .toPresignedUrl(
                                                fileIO,
                                                new Path("oss://bucket/table"),
                                                Duration.ofHours(1)))
                .isInstanceOf(RuntimeException.class)
                .hasMessageContaining("can not convert to descriptor");
        verifyNoInteractions(fileIO);
    }

    @Test
    public void testBlobRefReadsKnownLengthDirectly() {
        byte[] data = new byte[8194];
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) i;
        }
        TrackingSeekableInputStream inputStream = new TrackingSeekableInputStream(data);
        UriReader uriReader = uri -> inputStream;
        Blob blob = Blob.fromDescriptor(uriReader, new BlobDescriptor("test", 2, data.length - 2));

        assertThat(blob.toData()).isEqualTo(Arrays.copyOfRange(data, 2, data.length));
        assertThat(inputStream.readCalls).isEqualTo(1);
        assertThat(inputStream.maxRequestedBytes).isEqualTo(data.length - 2);
        assertThat(inputStream.closed).isTrue();
    }

    @Test
    public void testBlobRefRejectsTooLargeLengthBeforeOpeningStream() {
        AtomicBoolean streamOpened = new AtomicBoolean();
        UriReader uriReader =
                uri -> {
                    streamOpened.set(true);
                    return new ByteArraySeekableStream(new byte[0]);
                };
        long length = (long) Integer.MAX_VALUE - 7;
        Blob blob = Blob.fromDescriptor(uriReader, new BlobDescriptor("test", 0, length));

        assertThatThrownBy(blob::toData)
                .isInstanceOf(RuntimeException.class)
                .hasCauseInstanceOf(IOException.class)
                .hasMessageContaining("Blob is too large to materialize as byte[]");
        assertThat(streamOpened).isFalse();
    }

    private static class TrackingSeekableInputStream extends ByteArraySeekableStream {

        private int readCalls;
        private int maxRequestedBytes;
        private boolean closed;

        private TrackingSeekableInputStream(byte[] data) {
            super(data);
        }

        @Override
        public int read(byte[] bytes, int offset, int length) throws IOException {
            readCalls++;
            maxRequestedBytes = Math.max(maxRequestedBytes, length);
            return super.read(bytes, offset, length);
        }

        @Override
        public void close() throws IOException {
            closed = true;
            super.close();
        }
    }
}
