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

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

import java.net.URI;

import org.junit.Test;

import nz.org.riskscape.engine.DefaultEngine;
import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.auth.HttpHeaderSecret;
import nz.org.riskscape.engine.auth.Secret;
import nz.org.riskscape.engine.auth.SecretBuilder;
import nz.org.riskscape.engine.auth.SecretBuilders;
import nz.org.riskscape.engine.auth.Secrets;
import nz.org.riskscape.engine.bind.Parameter;
import nz.org.riskscape.engine.problem.GeneralProblems;
import nz.org.riskscape.problem.ProblemSink;

public class IniFileSecretBuilderTest extends ProjectTest {

  IniFileSecretBuilder builder;

  @Override
  protected void populateEngineWithDefaults(DefaultEngine newEngine) {
    super.populateEngineWithDefaults(newEngine);
    // this test uses HttpHeaderSecret for checking the behaviour of the builder, but that's just because it's on the
    // classpath - we're not really interested in its behaviour, just the general binding behaviour
    newEngine.getCollection(SecretBuilders.class).add(HttpHeaderSecret.BUILDER);
    builder = new IniFileSecretBuilder(newEngine);
  }

  @Test
  public void buildsValidSecret() {
    loadConfig("secrets.ini", ProblemSink.DEVNULL,
        """
        [foo1]
        framework = http-header
        header-name = foo
        secret-header-value = bar
        hostname = localhost
        """);

    builder.addSecret("foo1", config.getSection("foo1").get());

    HttpHeaderSecret built = getSecret("foo1").isA(HttpHeaderSecret.class).get();
    assertThat(built, allOf(
        hasProperty("id", is("foo1")),
        hasProperty("headerName", is("foo")),
        hasProperty("secretHeaderValue", is("bar")),
        hasProperty("hostname", is("localhost")),
        hasProperty("definedIn", is(URI.create("test:secrets.ini#I0L1C1")))
    ));
  }

  @Test
  public void hostnameDefaultsToID() {
    loadConfig("secrets.ini", ProblemSink.DEVNULL,
        """
        [riskscape.nz]
        framework = http-header
        header-name = foo
        secret-header-value = bar
        """);

    builder.addSecret("riskscape.nz", config.getSection("riskscape.nz").get());

    HttpHeaderSecret built = getSecret("riskscape.nz").isA(HttpHeaderSecret.class).get();
    assertThat(built, allOf(
        hasProperty("id", is("riskscape.nz")),
        hasProperty("headerName", is("foo")),
        hasProperty("secretHeaderValue", is("bar")),
        hasProperty("hostname", is("riskscape.nz")),
        hasProperty("definedIn", is(URI.create("test:secrets.ini#I0L1C1")))
    ));
  }

  @Test
  public void problemsIfSecretCannotBuildMissingParam() {
    loadConfig("secrets.ini", ProblemSink.DEVNULL,
        """
        [foo1]
        framework = http-header
        header-name = foo
        hostname = localhost
        """);

    builder.addSecret("foo1", config.getSection("foo1").get());

    // no problems yet, secret has not being built
    assertThat(sunkProblems, empty());

    // get all the secrets, this should build them and find problems.
    // note this is what HttpSecret will do when looking for HttpSecrets
    engine.getCollection(Secrets.class).getOfType(HttpHeaderSecret.class);
    // we look in sunk problems (cause the user will get them them from there)
    assertThat(sunkProblems, contains(
        Matchers.hasAncestorProblem(is(GeneralProblems.get()
            .required(HttpHeaderSecret.PARAMETER_SET.get("secret-header-value"))))
    ));
  }

  @Test
  public void problemsIfSecretCannotBuildMissingFramework() {
    // framework isn't a secret parameter, it's used by the ini builder so we test it separately
    loadConfig("secrets.ini", ProblemSink.DEVNULL,
        """
        [foo1]
        #framework = foo
        foo-param = foo one
        """);

    builder.addSecret("foo1", config.getSection("foo1").get());

    // no problems yet, secret has not being built
    assertThat(sunkProblems, empty());

    // get all the secrets, this should build them and find problems.
    // note this is what HttpSecret will do when looking for HttpSecrets
    engine.getCollection(Secrets.class).getOfType(HttpHeaderSecret.class);
    // we look in sunk problems (cause the user will get them them from there)
    assertThat(sunkProblems, contains(
        Matchers.hasAncestorProblem(is(GeneralProblems.get().required(Parameter.required("framework", Object.class))))
    ));
  }

  @Test
  public void problemsIfSecretCannotBuildUnknownFramework() {
    // framework isn't a secret parameter, it's used by the ini builder so we test it separately.
    loadConfig("secrets.ini", ProblemSink.DEVNULL,
        """
        [foo1]
        framework = bar
        foo-param = foo one
        """);

    builder.addSecret("foo1", config.getSection("foo1").get());

    // no problems yet, secret has not being built
    assertThat(sunkProblems, empty());

    // get all the secrets, this should build them and find problems.
    // note this is what HttpSecret will do when looking for HttpSecrets
    engine.getCollection(Secrets.class).getOfType(HttpHeaderSecret.class);
    // we look in sunk problems (cause the user will get them them from there)
    assertThat(sunkProblems, contains(
        Matchers.hasAncestorProblem(is(GeneralProblems.get().noSuchObjectExists("bar", SecretBuilder.class)))
    ));
  }

  Secret getSecret(String id) {
    return engine.getCollectionByClass(Secret.class)
        .get(id, engine.getProblemSink());
  }

}
