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

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

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.junit.Test;

import nz.org.riskscape.engine.RiskscapeException;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.problem.Problem.Severity;

public class ProblemsTest {

  @Test
  public void caughtFromAThrowable() throws Exception {
 // for non-RiskScapeExceptions, check the message is included, if present
    Problem withMessage = Problems.caught(new Throwable("a message"));
    Problem noMessage = Problems.caught(new RuntimeException((String) null));

    assertEquals(StandardCodes.CAUGHT_EXCEPTION, withMessage.getCode());
    assertEquals("java.lang.Throwable: a message", withMessage.getArguments()[0]);

    assertEquals(StandardCodes.CAUGHT_EXCEPTION, noMessage.getCode());
    assertEquals("java.lang.RuntimeException", noMessage.getArguments()[0]);
  }

  @Test
  public void caughtFromARiskscapeExceptionWithAProblem() throws Exception {
    Problem testProblem = Problems.get(GeneralProblems.class).noSuchObjectExists("foo", String.class);
    Throwable t = new RiskscapeException(testProblem);
    assertNull(t.getCause());
    Problem caught = Problems.caught(t);
    // the problem is ripped from the riskscapee xception
    assertSame(caught, testProblem);
    assertEquals("NO_SUCH_OBJECT_EXISTS", testProblem.getCode().name());
    assertNotEquals(StandardCodes.CAUGHT_EXCEPTION, caught.getCode());
    assertNull(caught.getException());
    assertNull(caught.findAnyException());
  }

  @Test
  public void caughtFromARiskscapeExceptionWithAProblemAndANestedException() throws Exception {
    Throwable nested = new Throwable("foo");
    Problem testProblem = Problems.get(GeneralProblems.class).noSuchObjectExists("foo", String.class).
        withException(nested);
    Throwable t = new RiskscapeException(testProblem);
    assertSame(t.getCause(), nested);
    Problem caught = Problems.caught(t);

    // the problem is ripped from the riskscape exception, unaltered
    assertSame(caught, testProblem);
    // note that the code is not caught - it's the original problem
    assertEquals("NO_SUCH_OBJECT_EXISTS", testProblem.getCode().name());
    assertNotEquals(StandardCodes.CAUGHT_EXCEPTION, caught.getCode());
    assertSame(nested, caught.getException());
  }

  @Test
  public void caughtFromAJavaExceptionWithANestedRiskscapeException() throws Exception {
    Problem testProblem = Problems.get(GeneralProblems.class).noSuchObjectExists("foo", String.class);
    Throwable nested = new RiskscapeException(testProblem);
    Exception ex = new ExecutionException(nested);
    Problem caught = Problems.caught(ex);

    // the caught problem is from the nested riskscape exception
    assertSame(caught, testProblem);
    assertEquals("NO_SUCH_OBJECT_EXISTS", testProblem.getCode().name());
    assertNotEquals(StandardCodes.CAUGHT_EXCEPTION, caught.getCode());
    assertNull(caught.getException());
    assertNull(caught.findAnyException());
  }

  @Test
  public void caughtFromANestedJavaExceptionWithNoProblem() throws Exception {
    Throwable nested = new Throwable("foo");
    Exception ex = new ExecutionException(nested);
    Problem caught = Problems.caught(ex);

    assertEquals(StandardCodes.CAUGHT_EXCEPTION, caught.getCode());
    assertEquals("java.util.concurrent.ExecutionException: java.lang.Throwable: foo", caught.getArguments()[0]);
    assertSame(caught.getException(), ex);
  }

  @Test
  public void caughtFromARiskscapeExceptionWithNoProblem() throws Exception {
    Throwable throwable = new RiskscapeException("a message");
    Problem caught = Problems.caught(throwable);

    assertEquals("a message", caught.getArguments()[0]);
    assertEquals(StandardCodes.CAUGHT_EXCEPTION, caught.getCode());
    assertSame(throwable, caught.getException());
  }

  @Test
  public void caughtFromARiskscapeExceptionWithNoProblemAndNoMessage() throws Exception {
    Problem caught = Problems.caught(new RiskscapeException((String) null));
    assertEquals("nz.org.riskscape.engine.RiskscapeException", caught.getArguments()[0]);
    assertEquals(StandardCodes.CAUGHT_EXCEPTION, caught.getCode());
  }

  @Test
  public void caughtFromAProblemExceptionWithOneProblem() throws Exception {
    Problem caught = Problems.caught(new ProblemException(Problems.foundWith("foo")));
    assertEquals(Problems.foundWith("foo"), caught);
  }

  @Test
  public void caughtFromAProblemExceptionWithManyProblems() throws Exception {
    Problem caught = Problems.caught(new ProblemException(Problems.foundWith("foo"), Problems.foundWith("bar")));
    assertEquals(Problems.toSingleProblem(Arrays.asList(Problems.foundWith("foo"), Problems.foundWith("bar"))), caught);
  }

  @Test
  public void canAccessExceptionInfoInNestedChildProblem() throws Exception {
    Throwable cause1 = new Throwable("foo");
    Problem testProblem = Problems.get(GeneralProblems.class).noSuchObjectExists("foo", String.class).
        withException(cause1);
    Throwable cause2 = new Throwable("bar");
    Throwable t = new RiskscapeException(testProblem, cause2);
    // a cause in the exception still overrides one in the problem
    assertSame(t.getCause(), cause2);

    Problem nested = Problems.foundWith("baz", Problems.caught(t));
    assertNull(nested.getException());
    // cause2 gets discarded when the exception is caught, so we see the original cause
    assertSame(nested.findAnyException(), cause1);

    // when the exception contains a nested problem, we can still access the original cause
    Throwable t2 = new RiskscapeException(nested);
    assertSame(t2.getCause(), cause1);
  }

  @Test
  public void toSingleProblemCanConvertAListOfProblemsInToASingleOne() throws Exception {
    List<Problem> allProblems = Arrays.asList(Problems.foundWith("foo"), Problems.foundWith("bar"));
    Problem singleProblem = Problems.toSingleProblem(allProblems);

    assertThat(singleProblem.getSeverity(), equalTo(Severity.ERROR));
    assertThat(singleProblem.getCode().name(), equalTo("MULTIPLE_PROBLEMS"));
    assertThat(singleProblem.getChildren(), equalTo(allProblems));
  }

  @Test
  public void toSingleProblemCanConvertAListOfProblemsWithMixedSeveritiesInToASingleOne() throws Exception {
    List<Problem> allProblems = Arrays.asList(
      Problems.foundWith("foo").withSeverity(Severity.INFO),
      Problems.foundWith("bar").withSeverity(Severity.WARNING)
    );
    Problem singleProblem = Problems.toSingleProblem(allProblems);

    assertThat(singleProblem.getSeverity(), equalTo(Severity.WARNING));
    assertThat(singleProblem.getCode().name(), equalTo("MULTIPLE_PROBLEMS"));
    assertThat(singleProblem.getChildren(), equalTo(allProblems));
  }

@Test
  public void toSingleProblemCanConvertASingleProblemInToOne() throws Exception {
    List<Problem> allProblems = Arrays.asList(Problems.foundWith("bar"));
    Problem singleProblem = Problems.toSingleProblem(allProblems);

    assertSame(singleProblem, allProblems.get(0));
  }
}
