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


import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;

import java.util.List;
import java.util.Optional;

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

import nz.org.riskscape.engine.typeset.TypeSet;

public class NullableTest {

  private Type mockType;
  private Nullable nullable;
  TypeSet typeSet = new TypeSet();

  @Test
  public void nullableSimpleTypes() {
    assertSame(Nullable.BOOLEAN, Nullable.of(Types.BOOLEAN));
    assertSame(Nullable.DECIMAL, Nullable.of(Types.DECIMAL));
    assertSame(Nullable.FLOATING, Nullable.of(Types.FLOATING));
    assertSame(Nullable.INTEGER, Nullable.of(Types.INTEGER));
    assertSame(Nullable.TEXT, Nullable.of(Types.TEXT));
  }

  @Test
  public void staticConstructorReturnsTheOriginalTypeIfPassedSomethingAlreadyNullable() {
    assertSame(Nullable.TEXT, Nullable.of(Nullable.TEXT));
  }

  @Test
  public void nullableStructs() {
    Struct struct = Struct.of("foo", Types.TEXT).build();
    Type nullableStruct = Nullable.of(struct);
    assertEquals(Optional.of(struct), nullableStruct.find(ContainingType.class).map(ct -> ct.getContainedType()));
  }

  @Test
  public void asStructCreatesANewStructWithNullableMembers() throws Exception {
    assertEquals(Struct.of("foo", Nullable.TEXT), Nullable.of(Struct.of("foo", Types.TEXT)).asStruct());
  }

  @Test
  public void nullableStructMembers() {
    Struct struct = Struct.of("foo", Nullable.TEXT).build();
    assertSame(Nullable.TEXT, struct.getEntry("foo").getType());
  }

  @Before
  public void setup() {
    mockType = mock(Type.class);
    when(mockType.find(Nullable.class)).thenReturn(Optional.empty());
    nullable = (Nullable) Nullable.of(mockType);
  }

  @Test
  public void returnsnullForNull() {
    assertNull(nullable.coerce(null));
    verify(mockType, never()).coerce(any());
  }

  @Test
  public void returnsWithCoercedValueForNonOptionalRawValue() {
    when(mockType.coerce(eq("foo"))).thenReturn("bar");
    assertEquals("bar", nullable.coerce("foo"));
  }

  @Test
  public void returnsWithCoercedValueForOptionalRawValue() {
    when(mockType.coerce(eq("foo"))).thenReturn("bar");
    assertEquals("bar", nullable.coerce(Optional.of("foo")));
  }

  @Test
  public void returnsNullEmptyWithOptionalEmpty() {
    assertEquals(null, nullable.coerce(Optional.empty()));
    verify(mockType, never()).coerce(any());
  }

  @Test
  public void anyCanCheckASetOfTypesForAnyNulls() throws Exception {
    assertFalse(Nullable.any());
    assertFalse(Nullable.any(Types.INTEGER));
    assertFalse(Nullable.any(Types.INTEGER, Types.ANYTHING));
    assertTrue(Nullable.any(Nullable.ANYTHING));
    assertTrue(Nullable.any(Types.INTEGER, Nullable.INTEGER));
  }

  @Test
  public void anyCanCheckAListOfTypesForAnyNulls() throws Exception {
    assertFalse(Nullable.any(List.of()));
    assertFalse(Nullable.any(List.of(Types.INTEGER)));
    assertFalse(Nullable.any(List.of(Types.INTEGER, Types.ANYTHING)));
    assertTrue(Nullable.any(List.of(Nullable.ANYTHING)));
    assertTrue(Nullable.any(List.of(Types.INTEGER, Nullable.INTEGER)));
  }

  @Test
  public void detectsNullableTypes() {
    assertThat(Nullable.is(Nullable.INTEGER), is(true));
    assertThat(Nullable.is(Nullable.ANYTHING), is(true));

    assertThat(Nullable.is(Types.INTEGER), is(false));
    assertThat(Nullable.is(Types.ANYTHING), is(false));
  }

  @Test
  public void detectsNullableLinkedTypes() {
    typeSet.add("n_integer", Nullable.INTEGER);
    typeSet.add("integer", Types.INTEGER);

    assertThat(Nullable.is(typeSet.getLinkedType("n_integer")), is(true));

    assertThat(Nullable.is(typeSet.getLinkedType("integer")), is(false));
  }

  @Test
  public void detectsNullableCanonicalTypes() {

    typeSet.add("n_integer", Nullable.INTEGER);
    typeSet.add("integer", Types.INTEGER);

    assertThat(Nullable.is(typeSet.get("n_integer")), is(true));
    assertThat(Nullable.is(typeSet.get("integer")), is(false));
  }

  @Test
  public void computeNullableAncestorDoesNothingWhenNonNullableArgs() throws Exception {
    assertEquals(
        Types.TEXT,
        typeSet.computeAncestorNoConversion(
            Types.TEXT,
            new WithinSet(Types.TEXT, "foo", "baz")
        )
    );

    assertEquals(
        Types.ANYTHING,
        typeSet.computeAncestorNoConversion(
            Types.TEXT,
            Types.INTEGER
        )
    );
  }

  @Test
  public void computeNullableAncestorWrapsResultInNullableIfOneArgNullable() throws Exception {
    assertEquals(
        Nullable.of(Types.TEXT),
        typeSet.computeAncestorNoConversion(
            Nullable.TEXT,
            new WithinSet(Types.TEXT, "foo", "baz")
        )
    );

    assertEquals(
        Nullable.ANYTHING,
        typeSet.computeAncestorNoConversion(
            Types.TEXT,
            Nullable.INTEGER
        )
    );
  }

  @Test
  public void computeNullableAncestorWrapsResultInNullableIfBothsArgsNullable() throws Exception {
    assertEquals(
        Nullable.of(Types.TEXT),
        typeSet.computeAncestorNoConversion(
            Nullable.TEXT,
            Nullable.of(new WithinSet(Types.TEXT, "foo", "baz"))
        )
    );

    assertEquals(
        Nullable.ANYTHING,
        typeSet.computeAncestorNoConversion(
            Nullable.TEXT,
            Nullable.INTEGER
        )
    );
  }

  @Test
  public void rewrapWrapsResultInNullableIfGivenArgWasNullable() throws Exception {
    // not nullable
    assertThat(
        Nullable.rewrap(Types.TEXT, t -> new WithinSet(t, "foo")),
        equalTo(new WithinSet(Types.TEXT, "foo"))
    );

    // nullable
    assertThat(
        Nullable.rewrap(Nullable.TEXT, t -> new WithinSet(t, "foo")),
        equalTo(Nullable.of(new WithinSet(Types.TEXT, "foo")))
    );
  }

}
