/*
 * RiskScape™ Copyright New Zealand Institute for Earth Science Limited
 * (Earth Sciences New Zealand) is distributed for research purposes only
 * under the terms of AGPLv3.
 *
 * RiskScape™ Copyright 2026 New Zealand Institute for Earth Science
 * Limited (Earth Sciences New Zealand). All rights reserved. Source code
 * available under the AGPLv3.
 * 
 * This program is free software: you can redistribute it and/or modify it under
 *  the terms of the GNU Affero General Public License as published by the Free
 *  Software Foundation, either version 3 of the License, or (at your option) any
 *  later version.
 * 
 * This program is distributed for RESEARCH PURPOSES ONLY, in the hope that it will
 * be useful for research and education initiatives.
 * 
 * If you are not a researcher, or you are a researcher who wishes to use this
 * program on terms other than AGPLv3 (including those who wish to restrict the
 * distribution of any source code created using this program), please contact:
 * https://riskscape.org.nz
 * 
 * This program is distributed WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Affero General Public License for more details.  You should have received a copy
 * of the GNU Affero General Public License along with this program.  If not, see
 * <http://www.gnu.org/licenses/>.
 * 
 * By way of summary only, under the AGPLv3:
 *     • Permissions of this strongest copyleft license are conditioned
 *       on making available complete source code of licensed works and
 *       modifications, which include larger works using a licensed work,
 *       under the same license.
 *     • Copyright and license notices must be preserved.
 *     • Contributors provide an express grant of patent rights.
 *     • When a modified version is used to provide a service over a
 *       network, the complete source code of the modified version must be made
 *       available.
 */
package nz.org.riskscape.engine.join;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.Before;
import org.junit.Test;

import nz.org.riskscape.engine.Tuple;
import nz.org.riskscape.engine.relation.ListRelation;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.engine.types.Types;

public class HashIndexerTest extends BaseIndexerTest {

  Struct type = Struct.of("key", Types.TEXT, "value", Types.TEXT);

  Struct lhsType = type.parent("lhs");
  Struct rhsType = type.parent("rhs");

  List<Tuple> lhsValues = new ArrayList<>();
  List<Tuple> rhsValues = new ArrayList<>();

  ListRelation lhs = new ListRelation(type, lhsValues);
  ListRelation rhs = new ListRelation(type, rhsValues);
  Joiner join;

  JoinCondition joinCondition;
  HashIndexer indexer;

  @Before
  public void setup() {
    //init the join with a cartisian join condition
    join = new Joiner(lhsType, rhsType, JoinCondition.CARTESIAN);
  }

  public void setupJoin() {
    //Update join with new join condition
    join = join.withJoinConditon(joinCondition);
    indexer = new HashIndexer(join, expressionRealizer, 10);

    if (!indexer.isUsable()) {
      //Don't populate an unusable index
      return;
    }
    for (Tuple toIndex : rhsValues) {
      indexer.addToIndex(toIndex);
    }
  }

  public Tuple tuple(Struct parentType, String key, String value) {
    return Tuple.ofValues(parentType, Tuple.ofValues(type, key, value));
  }

  @Test
  public void testEqualsJoin_NoMatch() throws Exception {
    rhsValues.add(tuple(rhsType, "car", "toyota"));

    joinCondition = setupJoinCondition(toFilter("lhs.key = rhs.key"), join.getJoinedType());
    setupJoin();

    assertTrue(indexer.isUsable());

    List<Tuple> collected = indexer.createRhsIterator(
        Tuple.of(lhsType, "lhs", Tuple.ofValues(type, "truck", "")))
        .collect(Collectors.toList());

    assertThat(collected, is(empty()));
  }

  @Test
  public void testEqualsJoin_WithMatch() throws Exception {
    rhsValues.add(tuple(rhsType, "car", "toyota"));
    rhsValues.add(tuple(rhsType, "truck", "daf"));
    rhsValues.add(tuple(rhsType, "car", "subaru"));


    joinCondition = setupJoinCondition(toFilter("lhs.key = rhs.key"), join.getJoinedType());
    setupJoin();

    assertThat(indexer.isUsable(), is(true));

    List<Tuple> collected = indexer.createRhsIterator(
        Tuple.of(lhsType, "lhs", Tuple.ofValues(type, "car", "")))
        .collect(Collectors.toList());

    assertThat(collected, contains(
        tuple(rhsType, "car", "toyota"),
        tuple(rhsType, "car", "subaru")
    ));
  }

  @Test
  public void testComparisonJoin_WithNullable() throws Exception {

    lhsType = Struct.of("lhs", Nullable.INTEGER);
    rhsType = Struct.of("rhs", Types.INTEGER);

    rhsValues.add(Tuple.ofValues(rhsType, (Long) null));
    rhsValues.add(Tuple.ofValues(rhsType, 2L));
    setup();    // we've messed with the types so need to setup again
    joinCondition = setupJoinCondition(toFilter("rhs > lhs"), join.getJoinedType());
    setupJoin();

    assertThat(indexer.isUsable(), is(true));

    List<Tuple> collected = indexer.createRhsIterator(
        Tuple.ofValues(lhsType, 1L))
        .collect(Collectors.toList());

    assertThat(collected, contains(
      Tuple.ofValues(rhsType, 2L)
    ));
  }

  @Test
  public void findsFirstUsableCondition() throws Exception {
    rhsValues.add(tuple(rhsType, "car", "toyota"));
    rhsValues.add(tuple(rhsType, "truck", "daf"));
    rhsValues.add(tuple(rhsType, "car", "subaru"));

    //This join condition is incorrect in many ways, but the indexer does not need to validate or care
    //This is to show that the indexer ignores the first part of the expression(the or) and the finds
    //the trailling part.
    joinCondition = setupJoinCondition(toFilter("((lhs.key = '2') or (rhs.key = '4')) and (lhs.key = rhs.key)"),
        join.getJoinedType());
    setupJoin();

    assertThat(indexer.isUsable(), is(true));

    List<Tuple> collected = indexer.createRhsIterator(
        Tuple.of(lhsType, "lhs", Tuple.ofValues(type, "car", "")))
        .collect(Collectors.toList());

    assertThat(collected, contains(
        tuple(rhsType, "car", "toyota"),
        tuple(rhsType, "car", "subaru")
    ));
  }

  @Test
  public void expressionsInLhsAndRhsAreOkay() throws Exception {
    rhsValues.add(tuple(rhsType, "car", "toyota"));
    rhsValues.add(tuple(rhsType, "truck", "daf"));
    rhsValues.add(tuple(rhsType, "car", "subaru"));

    joinCondition = setupJoinCondition(toFilter("str_length(lhs.key) = str_length(rhs.key)"), join.getJoinedType());
    setupJoin();

    assertThat(indexer.isUsable(), is(true));

    List<Tuple> collected = indexer.createRhsIterator(
        Tuple.of(lhsType, "lhs", Tuple.ofValues(type, "123", "")))
        .collect(Collectors.toList());

    assertThat(collected, contains(
        tuple(rhsType, "car", "toyota"),
        tuple(rhsType, "car", "subaru")
    ));
  }

  @Test
  public void canIndexAGreaterThanEqualsComparision() throws Exception {
    rhsValues.add(tuple(rhsType, "car", "toyota"));
    rhsValues.add(tuple(rhsType, "truck", "daf"));
    rhsValues.add(tuple(rhsType, "car", "subaru"));

    joinCondition = setupJoinCondition(toFilter("str_length(lhs.key) >= str_length(rhs.key)"), join.getJoinedType());
    setupJoin();

    assertThat(indexer.isUsable(), is(true));

    List<Tuple> collected = indexer.createRhsIterator(
        Tuple.of(lhsType, "lhs", Tuple.ofValues(type, "123", "")))
        .collect(Collectors.toList());

    assertThat(collected, containsInAnyOrder(
        tuple(rhsType, "car", "toyota"),
        tuple(rhsType, "car", "subaru")
    ));
  }

  @Test
  public void canIndexAGreaterThanEqualsComparision1() throws Exception {
    rhsValues.add(tuple(rhsType, "car", "toyota"));
    rhsValues.add(tuple(rhsType, "truck", "daf"));
    rhsValues.add(tuple(rhsType, "car", "subaru"));

    joinCondition = setupJoinCondition(toFilter("str_length(rhs.key) <= str_length(lhs.key)"), join.getJoinedType());
    setupJoin();

    assertThat(indexer.isUsable(), is(true));

    List<Tuple> collected = indexer.createRhsIterator(
        Tuple.of(lhsType, "lhs", Tuple.ofValues(type, "123", "")))
        .collect(Collectors.toList());

    assertThat(collected, containsInAnyOrder(
        tuple(rhsType, "car", "toyota"),
        tuple(rhsType, "car", "subaru")
    ));
  }

  @Test
  public void cannotIndexConstantTrue() throws Exception {
    // Constant true cannot be indexed as there is on effective left/right sides.
    joinCondition = setupJoinCondition(toFilter("true"), join.getJoinedType());
    setupJoin();

    assertThat(indexer.isUsable(), is(false));
  }
}
