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

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

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import nz.org.riskscape.config.ConfigString;
import nz.org.riskscape.engine.auth.HttpSecret.Request;
import nz.org.riskscape.engine.bind.BindingContext;
import nz.org.riskscape.engine.bind.BoundParameters;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.bind.ParameterSet;
import nz.org.riskscape.problem.ResultOrProblems;

public abstract class HttpSecretTest<T extends HttpSecret> {

  public Map<String, ? super Object> params = new HashMap<>(Map.of(
      "hostname", "bar.com",
      "id", "foo"
  ));

  public BindingContext context = mock(BindingContext.class);

  public T secret;

  public ResultOrProblems<Secret> bindingResult;

  public BoundParameters boundParameters;

  public URI idLocation = URI.create("file:///secrets.ini");

  public Request request;

  @Before
  public void setup() {
    // binding just returns what it was given, by default
    Parameter idParameter = getSecretBuilder().getParameters().get("id");

    // mimic config string behaviour in actual binders
    when(context.bind(any(), Mockito.eq(idParameter)))
        .thenAnswer(i -> ResultOrProblems.of(ConfigString.wrap(idLocation, (String) i.getArguments()[0])));
  }

  @SuppressWarnings("unchecked")
  public T buildSecret() {
    SecretBuilder secretBuilder = getSecretBuilder();

    boundParameters =
        secretBuilder.getParameters().bind(context, ParameterSet.normaliseParameterMap(params));

    bindingResult = getSecretBuilder().getBuilder().apply(boundParameters);

    if (bindingResult.isPresent()) {
      secret = (T) bindingResult.get();
    } else {
      secret = null;
    }

    return secret;
  }

  public abstract SecretBuilder getSecretBuilder();

  public Request applySecret(String uriString) {
    Secrets secrets = new Secrets();
    secrets.add(secret);
    request = HttpSecret.getRequest(URI.create(uriString), secrets);

    return request;
  }

  /*
   * Test cases that should apply to all HttpSecrets
   */

  @Test
  public void canMatchSecret() {
    buildSecret();
    // wrong scheme
    assertFalse(secret.matches(URI.create("file://" + secret.getHostname() + getMatchingPath())));
    // insecure - http not matched by default
    assertFalse(secret.matches(URI.create("http://" + secret.getHostname() + getMatchingPath())));

    // wrong hostname
    assertFalse(secret.matches(URI.create("https://baz.com" + getMatchingPath())));

    // suffixed
    assertFalse(secret.matches(URI.create("https://" + secret.getHostname() + ".au"
        + getMatchingPath())));

    // don't match subdomains by default
    assertFalse(secret.matches(URI.create("https://baz." + secret.getHostname()
      + getMatchingPath())));

    // exact match
    assertTrue(secret.matches(URI.create("https://" + secret.getHostname() + getMatchingPath())));

    // trailing paths are allowed
    assertTrue(secret.matches(URI.create("https://" + secret.getHostname() + getMatchingPath()
      + "/baz.html")));
  }

  @Test
  public void canMatchSecretWhenHostnameContainsURI() {
    String hostname = "bar.com";
    for (String suffix : new String[] {"", "/some/file"}) {
      params.put("hostname", "https://" + hostname + suffix);
      buildSecret();
      // wrong scheme
      assertFalse(secret.matches(URI.create("file://" + hostname + getMatchingPath())));
      // insecure - http not matched by default
      assertFalse(secret.matches(URI.create("http://" + hostname + getMatchingPath())));

      // wrong hostname
      assertFalse(secret.matches(URI.create("https://baz.com" + getMatchingPath())));

      // suffixed
      assertFalse(secret.matches(URI.create("https://" + hostname + ".au"
          + getMatchingPath())));

      // don't match subdomains by default
      assertFalse(secret.matches(URI.create("https://baz." + hostname
          + getMatchingPath())));

      // exact match
      assertTrue(secret.matches(URI.create("https://" + hostname + getMatchingPath())));

      // trailing paths are allowed
      assertTrue(secret.matches(URI.create("https://" + hostname + getMatchingPath()
          + "/baz.html")));
    }
  }

  @Test
  public void canMatchSecretBySubdomain() {
    params.put("allow-subdomains", true);
    buildSecret();

    // subdomain
    assertTrue(secret.matches(URI.create("https://baz." + secret.getHostname() + getMatchingPath())));
    assertTrue(secret.matches(URI.create("https://baz." + secret.getHostname() + getMatchingPath()
      + "/some-resource")));

    // two-level subdomain
    assertTrue(secret.matches(URI.create("https://foo.baz." + secret.getHostname()
      + getMatchingPath())));

    // but not suffixes
    assertFalse(secret.matches(URI.create("https://" + secret.getHostname() + ".com"
        + getMatchingPath())));
  }

  @Test
  public void canAllowInsecureHttp() {
    params.put("allow-http", true);
    buildSecret();
    // can now match http requests
    assertTrue(secret.matches(URI.create("http://" + secret.getHostname() + getMatchingPath())));
    // as well as the original https
    assertTrue(secret.matches(URI.create("https://" + secret.getHostname() + getMatchingPath())));
    // other protos not affected
    assertFalse(secret.matches(URI.create("file:///" + secret.getHostname() + getMatchingPath())));
  }

  @Test
  public void derivedInComesFromIdConfigString() throws Exception {
    // it's a little buried/subtle, but in the test setup we mimic the binding behaviour for when we bind a map of
    // ConfigStrings to a ParameterSet - the getDerivedIn() should return the URI that was threaded in from the ini file
    buildSecret();

    assertThat(secret.getDefinedIn(), equalTo(idLocation));
  }

  @Test
  public void secretNotLeakedByToString() {
    buildSecret();

    assertThat(secret.toString(), not(containsString(getSecretValue())));
  }

  // return the secret value from the secret implementation - solely here so we can make sure the secret isn't leaked
  // in to string methods
  protected abstract String getSecretValue();

  // added for secrets that match on path (e.g. KoordinatesKeySecret)
  protected String getMatchingPath() {
    return "";
  }
}
