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

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;

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

import com.google.common.collect.ImmutableMap;

import lombok.RequiredArgsConstructor;

import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.problem.Problem;
import nz.org.riskscape.problem.Problems;
import nz.org.riskscape.problem.ResultOrProblems;

public class ParameterSetTest {

  @RequiredArgsConstructor
  public static class Wrapped {
    private final String wrapped;

    @Override
    public String toString() {
      return wrapped;
    }
  }

  BindingContext context = mock(BindingContext.class);

  @Before
  public void setup() {
    when(context.bind(any(Object.class), any(Parameter.class))).thenAnswer(a -> {
      String input = a.getArgument(0).toString();
      List<Problem> warnings = new ArrayList<>();
      if ("warning".equals(input)) {
        warnings.add(Problem.warning("warning will robinson"));
      }
      return ResultOrProblems.of(input + " yay", warnings);
    });
  }

  @Test
  public void canBindAnOptionalParameter() throws Exception {
    ParameterSet subject = ParameterSet.from(Parameter.optional("foo", Wrapped.class));

    BoundParameters result = subject.bind(context, map("foo", "bar"));
    assertTrue(result.isValid());

    assertEquals("bar yay", result.getValue("foo"));

    // check flatmap to a successful result
    assertEquals(
        ResultOrProblems.of("cool"),
        result.flatMap(bp -> ResultOrProblems.of("cool"))
    );

    // check flatmap to an unsuccessful result
    assertTrue(
        result.flatMap(bp -> ResultOrProblems.failed(Problems.caught(new RuntimeException()))).hasErrors()
    );

    // nothing is ok too
    result = subject.bind(context, Collections.emptyMap());
    assertTrue(result.isValid());
    assertNull(result.getValue("foo"));

    // multiple values is a problem
    result = subject.bind(context, map("foo", "bar", "baz"));
    assertFalse(result.isValid());

    assertEquals("bar yay", result.getValue("foo"));
    assertThat(
        result.getValidationProblems(),
        contains(equalTo(ParamProblems.get().wrongNumberGiven("foo", "0..1", 2)))
    );

    // check flat map for a failed result
    assertFalse(result.flatMap(bp -> ResultOrProblems.of(bp)).isPresent());
  }

  @Test
  public void canBindARequiredParameter() {
    ParameterSet subject = ParameterSet.from(Parameter.required("foo", Wrapped.class));

    BoundParameters result = subject.bind(context, map("foo", "bar"));
    assertTrue(result.isValid());

    assertEquals("bar yay", result.getValue("foo"));

    // nothing is bad
    result = subject.bind(context, Collections.emptyMap());
    assertFalse(result.isValid());

    assertNull(result.getValue("foo"));
    assertThat(
        result.getValidationProblems(),
        contains(equalTo(GeneralProblems.get().required(subject.get("foo"))))
    );

    // multiple values is bad
    result = subject.bind(context, map("foo", "bar", "baz"));
    assertFalse(result.isValid());

    assertEquals("bar yay", result.getValue("foo"));
    assertThat(
        result.getValidationProblems(),
        contains(equalTo(ParamProblems.get().wrongNumberGiven("foo", "1", 2)))
    );
  }

  @Test
  public void canBindAnAtLeastOneParameter() throws Exception {
    ParameterSet subject = ParameterSet.from(Parameter.range("foo", Wrapped.class, 1, Integer.MAX_VALUE));

    BoundParameters result = subject.bind(context, map("foo", "bar"));
    assertTrue(result.isValid());

    assertEquals(Arrays.asList("bar yay"), result.getValues("foo"));

    // nothing is bad
    result = subject.bind(context, Collections.emptyMap());
    assertFalse(result.isValid());

    assertTrue(result.getValues("foo").isEmpty());
    assertThat(
        result.getValidationProblems(),
        contains(equalTo(GeneralProblems.get().required(subject.get("foo"))))
    );

    // map maps to a failed result
    assertTrue(result.map(bp -> bp.getValues("foo")).hasErrors());
    assertFalse(result.map(bp -> bp.getValues("foo")).isPresent());

    // multiple values is fine
    result = subject.bind(context, map("foo", "bar", "baz"));
    assertTrue(result.isValid());

    assertEquals(Arrays.asList("bar yay", "baz yay"), result.getValues("foo"));
  }

  @Test
  public void canBindAZeroToManyParameter() throws Exception {
    ParameterSet subject = ParameterSet.from(Parameter.range("foo", Wrapped.class, 0, Integer.MAX_VALUE));

    BoundParameters result = subject.bind(context, map("foo", "bar"));
    assertTrue(result.isValid());

    assertEquals(Arrays.asList("bar yay"), result.getValues("foo"));

    // nothing is fine
    result = subject.bind(context, Collections.emptyMap());
    assertTrue(result.isValid());

    assertEquals(Arrays.asList(), result.getValues("foo"));

    // multiple values is fine
    result = subject.bind(context, map("foo", "bar", "baz"));
    assertTrue(result.isValid());

    // check map works OK for this one
    assertEquals(
      ResultOrProblems.of(Arrays.asList("bar yay", "baz yay")),
      result.map(bp -> bp.getValues("foo"))
    );
  }

  @Test
  public void canBindParameterWithWarning() throws Exception {
    ParameterSet subject = ParameterSet.from(Parameter.required("foo", Wrapped.class));

    BoundParameters result = subject.bind(context, map("foo", "warning"));
    assertTrue(result.isValid());

    assertEquals(
      ResultOrProblems.of(Arrays.asList("warning yay")),
      result.map(bp -> bp.getValues("foo"))
    );

    assertThat(result.getValidationProblems(), contains(
        Problem.warning("warning will robinson")
    ));
  }

  @Test
  public void anUnboundValueOfTheCorrectTypeIsSetDirectly() throws Exception {
    ParameterSet subject = ParameterSet.from(Parameter.required("foo", Wrapped.class));

    Wrapped wrapped = new Wrapped("bar");
    BoundParameters result = subject.bind(context, map("foo", wrapped));
    assertTrue(result.isValid());

    assertSame(wrapped, result.getValue("foo"));
    verifyZeroInteractions(context);
  }

  @Test
  public void aBindingExceptionIsCaughtAndTheProblemReturned() throws Exception {
    ParameterSet subject = ParameterSet.from(Parameter.required("foo", Wrapped.class));
    Problem problem = ParamProblems.get().mutuallyExclusive("foo", "bar");

    when(context.bind(eq("bar"), any(Parameter.class)))
      .thenReturn(ResultOrProblems.failed(problem));

    BoundParameters result = subject.bind(context, map("foo", "bar"));

    assertFalse(result.isValid());
    assertTrue(result.getValues("foo").isEmpty());

    assertThat(
      result.getValidationProblems(),
      contains(problem)
    );
  }

  @Test(expected = RuntimeException.class)
  public void anyOtherSortOfExceptionIsStillThrown() throws Exception {
    ParameterSet subject = ParameterSet.from(Parameter.required("foo", Wrapped.class));

    when(context.bind(eq("bar"), any(Parameter.class))).thenThrow(new RuntimeException("great"));

    // bind should only try to catch ParameterBindingExceptions
    subject.bind(context, map("foo", "bar"));
  }

  @Test
  public void extraneousParametersCanBeFetched() throws Exception {
    ParameterSet subject = ParameterSet.from(Parameter.required("foo", String.class));

    BoundParameters parameters = subject
        .bind(context, ImmutableMap.of("foo", Arrays.asList("bar"), "foo2", Arrays.asList("bar")));

    assertTrue(parameters.isValid());

    assertEquals("bar", parameters.getValue("foo"));
    assertEquals(map("foo2", "bar"), parameters.getExtraneous());
  }

  @Test
  public void parameterSetsAreEqualIfTheirListOfParametersIsEqual() throws Exception {
    ParameterSet setA = ParameterSet.from(
      Parameter.required("foo", String.class),
      Parameter.required("bar", String.class)
    );
    ParameterSet setB = ParameterSet.from(
      Parameter.required("foo", String.class),
      Parameter.required("bar", String.class)
    );

    assertEquals(setA, setB);

    assertNotEquals(
        setA,
        ParameterSet.from(
            Parameter.required("foo", String.class),
            Parameter.required("bar", Long.class)
        )
    );

    assertNotEquals(
        setA,
        ParameterSet.from(
            Parameter.required("foo", String.class),
            Parameter.required("bar", String.class),
            Parameter.required("baz", String.class)
        )
    );

    assertEquals(
      setA,
      ParameterSet.from(
        Parameter.required("bar", String.class),
        Parameter.required("foo", String.class)
      )
    );
  }

  @Test(expected=IllegalArgumentException.class)
  public void addingTwoParametersWithTheSameNameChokes() throws Exception {
    ParameterSet.from(
      Parameter.required("foo", String.class),
      Parameter.required("foo", Integer.class)
    );

  }

  private Map<String, List<?>> map(String key, Object... values) {
    return ImmutableMap.of(key, Arrays.asList(values));
  }
}
