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

import static org.apache.ignite.internal.TestWrappers.unwrapTableImpl;
import static org.apache.ignite.internal.catalog.CatalogService.DEFAULT_STORAGE_PROFILE;
import static org.apache.ignite.internal.sql.engine.util.SqlTestUtils.executeUpdate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

import org.apache.ignite.Ignite;
import org.apache.ignite.internal.ClusterPerTestIntegrationTest;
import org.apache.ignite.table.KeyValueView;
import org.apache.ignite.table.Table;
import org.junit.jupiter.api.Test;

class ItPartitionStoragesTest extends ClusterPerTestIntegrationTest {
    private static final String TABLE_NAME = "TEST_TABLE";

    @Override
    protected int initialNodes() {
        return 2;
    }

    @Test
    void onlyCreatesPartitionStoragesForPartitionsAssignedToNode() {
        createTableWith1ReplicaAnd1Partition();

        putToTable();

        int partitionStoragesCount = cluster.runningNodes()
                .map(node -> unwrapTableImpl(table(node)).internalTable())
                .mapToInt(internalTable -> internalTable.storage().getMvPartition(0) != null ? 1 : 0)
                .sum();

        assertThat(partitionStoragesCount, is(1));
    }

    private void createTableWith1ReplicaAnd1Partition() {
        cluster.doInSession(0, session -> {
            executeUpdate(
                    "create zone test_zone (partitions 1, replicas 1) storage profiles ['" + DEFAULT_STORAGE_PROFILE + "'];",
                    session
            );
            executeUpdate("create table " + TABLE_NAME + " (key int primary key, val varchar(20))"
                    + " zone TEST_ZONE storage profile '" + DEFAULT_STORAGE_PROFILE + "';", session);
        });
    }

    private void putToTable() {
        KeyValueView<Integer, String> keyValueView = table().keyValueView(Integer.class, String.class);
        keyValueView.put(null, 1, "one");
    }

    private Table table() {
        return table(cluster.aliveNode());
    }

    private static Table table(Ignite node) {
        return node.tables().table(TABLE_NAME);
    }
}
