/*
 * 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.fluss.server.kv.rowmerger;

import org.apache.fluss.metadata.DeleteBehavior;
import org.apache.fluss.metadata.Schema;
import org.apache.fluss.record.BinaryValue;
import org.apache.fluss.row.TimestampLtz;
import org.apache.fluss.row.TimestampNtz;
import org.apache.fluss.types.DataType;
import org.apache.fluss.types.DataTypes;
import org.apache.fluss.types.RowType;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

import static org.apache.fluss.testutils.DataTestUtils.compactedRow;
import static org.assertj.core.api.Assertions.assertThat;

/** Test for {@link VersionedRowMerger}. */
class VersionedRowMergerTest {

    static Stream<Arguments> parameters() {
        return Stream.of(
                Arguments.of(
                        DataTypes.INT(),
                        Arrays.asList(
                                TestSpec.of(1, 2, "new"),
                                TestSpec.of(2, 1, "old"),
                                TestSpec.of(1, 1, "new"))),
                Arguments.of(
                        DataTypes.BIGINT(),
                        Arrays.asList(
                                TestSpec.of(1L, 2L, "new"),
                                TestSpec.of(2L, 1L, "old"),
                                TestSpec.of(1L, 1L, "new"))),
                Arguments.of(
                        DataTypes.TIMESTAMP(),
                        Arrays.asList(
                                TestSpec.of(
                                        timestampNtz("2025-01-10T12:00:00.123"),
                                        timestampNtz("2025-01-10T12:00:10.123"),
                                        "new"),
                                TestSpec.of(
                                        timestampNtz("2025-01-10T12:00:00.123"),
                                        timestampNtz("2025-01-10T12:00:00.122"),
                                        "old"),
                                TestSpec.of(
                                        timestampNtz("2025-01-10T12:00:00.123"),
                                        timestampNtz("2025-01-10T12:00:00.123"),
                                        "new"))),
                Arguments.of(
                        DataTypes.TIMESTAMP(9),
                        Arrays.asList(
                                TestSpec.of(
                                        timestampNtz("2025-01-10T12:00:00.123456789"),
                                        timestampNtz("2025-01-10T12:00:10.123456789"),
                                        "new"),
                                TestSpec.of(
                                        timestampNtz("2025-01-10T12:00:00.123456789"),
                                        timestampNtz("2025-01-10T12:00:00.123456788"),
                                        "old"),
                                TestSpec.of(
                                        timestampNtz("2025-01-10T12:00:00.123456789"),
                                        timestampNtz("2025-01-10T12:00:00.123456789"),
                                        "new"))),
                Arguments.of(
                        DataTypes.TIMESTAMP_LTZ(),
                        Arrays.asList(
                                TestSpec.of(
                                        timestampLtz("2025-01-10T12:00:00.123"),
                                        timestampLtz("2025-01-10T12:00:10.123"),
                                        "new"),
                                TestSpec.of(
                                        timestampLtz("2025-01-10T12:00:00.123"),
                                        timestampLtz("2025-01-10T12:00:00.122"),
                                        "old"),
                                TestSpec.of(
                                        timestampLtz("2025-01-10T12:00:00.123"),
                                        timestampLtz("2025-01-10T12:00:00.123"),
                                        "new"))),
                Arguments.of(
                        DataTypes.TIMESTAMP_LTZ(9),
                        Arrays.asList(
                                TestSpec.of(
                                        timestampLtz("2025-01-10T12:00:00.123456789"),
                                        timestampLtz("2025-01-10T12:00:10.123456789"),
                                        "new"),
                                TestSpec.of(
                                        timestampLtz("2025-01-10T12:00:00.123456789"),
                                        timestampLtz("2025-01-10T12:00:00.123456788"),
                                        "old"),
                                TestSpec.of(
                                        timestampLtz("2025-01-10T12:00:00.123456789"),
                                        timestampLtz("2025-01-10T12:00:00.123456789"),
                                        "new"))));
    }

    @ParameterizedTest
    @MethodSource("parameters")
    void testAllTypes(DataType type, List<TestSpec> testSpecs) {
        Schema schema =
                Schema.newBuilder().column("a", type).column("b", DataTypes.STRING()).build();
        RowType rowType = schema.getRowType();
        VersionedRowMerger merger = new VersionedRowMerger("a", DeleteBehavior.DISABLE);
        merger.configureTargetColumns(null, (short) 1, schema);

        for (TestSpec testSpec : testSpecs) {
            BinaryValue oldValue = binaryValue(rowType, new Object[] {testSpec.oldValue, "dummy"});
            BinaryValue newValue = binaryValue(rowType, new Object[] {testSpec.newValue, "dummy"});
            BinaryValue mergedValue = merger.merge(oldValue, newValue);
            if (testSpec.expected.equals("old")) {
                assertThat(mergedValue).isSameAs(oldValue);
            } else if (testSpec.expected.equals("new")) {
                assertThat(mergedValue).isSameAs(newValue);
            } else {
                throw new IllegalArgumentException("Unknown expected value: " + testSpec.expected);
            }
        }
    }

    @Test
    void testMergeWithNullOldValueReturnsNewValue() {
        Schema schema =
                Schema.newBuilder()
                        .column("a", DataTypes.INT())
                        .column("b", DataTypes.STRING())
                        .build();
        RowType rowType = schema.getRowType();
        VersionedRowMerger merger = new VersionedRowMerger("a", DeleteBehavior.DISABLE);
        merger.configureTargetColumns(null, (short) 1, schema);

        BinaryValue newValue = binaryValue(rowType, new Object[] {42, "first"});
        BinaryValue result = merger.merge(null, newValue);
        assertThat(result).isSameAs(newValue);
    }

    @Test
    void testNormal() {
        Schema schema =
                Schema.newBuilder()
                        .column("a", DataTypes.INT())
                        .column("b", DataTypes.STRING())
                        .build();
        VersionedRowMerger merger = new VersionedRowMerger("a", DeleteBehavior.DISABLE);
        merger.configureTargetColumns(null, (short) 1, schema);

        assertThat(merger.deleteBehavior()).isEqualTo(DeleteBehavior.DISABLE);
        assertThat(merger.configureTargetColumns(null, (short) 1, schema)).isSameAs(merger);
    }

    @Test
    void testSchemaChange() {
        Schema schema =
                Schema.newBuilder()
                        .column("a", DataTypes.INT())
                        .column("b", DataTypes.STRING())
                        .build();
        RowType rowType = schema.getRowType();
        VersionedRowMerger merger = new VersionedRowMerger("a", DeleteBehavior.DISABLE);
        merger.configureTargetColumns(null, (short) 1, schema);
        BinaryValue oldValue = binaryValue(rowType, new Object[] {11, "dummy"});
        BinaryValue newValue = binaryValue(rowType, new Object[] {2, "dummy"});
        assertThat(merger.merge(oldValue, newValue)).isSameAs(oldValue);

        Schema schema2 =
                Schema.newBuilder()
                        .fromColumns(
                                Arrays.asList(
                                        new Schema.Column("a", DataTypes.INT(), null, (short) 0),
                                        new Schema.Column("b", DataTypes.STRING(), null, (short) 1),
                                        // add new column at end
                                        new Schema.Column(
                                                "c", DataTypes.STRING(), null, (short) 2)))
                        .build();
        rowType = schema2.getRowType();
        merger.configureTargetColumns(null, (short) 2, schema2);

        newValue = binaryValue(rowType, new Object[] {2, "dummy", "a"});
        // version is smaller than old value
        assertThat(merger.merge(oldValue, newValue)).isSameAs(oldValue);
        newValue = binaryValue(rowType, new Object[] {20, "dummy", "b"});
        // version is greater than old value
        assertThat(merger.merge(oldValue, newValue)).isSameAs(newValue);
    }

    private static TimestampNtz timestampNtz(String timestamp) {
        return TimestampNtz.fromLocalDateTime(LocalDateTime.parse(timestamp));
    }

    private static TimestampLtz timestampLtz(String timestamp) {
        Instant instant = LocalDateTime.parse(timestamp).toInstant(ZoneOffset.UTC);
        return TimestampLtz.fromInstant(instant);
    }

    private static BinaryValue binaryValue(RowType rowType, Object[] objects) {
        int schemaId = rowType.getFieldCount() == 2 ? 1 : 2;
        return new BinaryValue((short) schemaId, compactedRow(rowType, objects));
    }

    /** Test specification for {@link VersionedRowMerger}. */
    private static class TestSpec {
        private final Object oldValue;
        private final Object newValue;
        private final String expected;

        private TestSpec(Object oldValue, Object newValue, String expected) {
            this.oldValue = oldValue;
            this.newValue = newValue;
            this.expected = expected;
        }

        public static TestSpec of(Object oldValue, Object newValue, String expected) {
            return new TestSpec(oldValue, newValue, expected);
        }
    }
}
