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

import static nz.org.riskscape.engine.Assert.*;

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

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.google.common.collect.Lists;

import nz.org.riskscape.engine.Matchers;
import nz.org.riskscape.engine.ProjectTest;
import nz.org.riskscape.engine.RiskscapeIOException;
import nz.org.riskscape.engine.auth.HttpHeaderSecret;
import nz.org.riskscape.engine.auth.HttpSecret;
import nz.org.riskscape.engine.auth.SecretProblems;
import nz.org.riskscape.engine.auth.Secrets;
import nz.org.riskscape.engine.resource.Resource;
import nz.org.riskscape.engine.resource.ResourceProblems;

public class HttpResourceLoaderTest extends ProjectTest {

  HttpResourceLoader subject;
  Resource resource;
  Resource.Options options = Resource.SECURE_OPTIONS;
  Secrets secrets = new Secrets();


  HttpURLConnection mockConnection = mock(HttpURLConnection.class);

  HttpResourceLoader mockingSubject = new HttpResourceLoader(engine) {
    @Override
    HttpURLConnection getConnection(HttpSecret.Request request) throws IOException {
      return mockConnection;
    }
  };

  public HttpResourceLoaderTest() throws Exception {
    engine.registerCollection(secrets);
    subject = new HttpResourceLoader(engine);

    secrets.add(secret("secure", "localhost", "foo", false, false));
    secrets.add(secret("secureWithSubDomains", "localhost", "bar", true, false));
    secrets.add(secret("insecure", "localhost", "baz", false, true));
    secrets.add(secret("mock", "mocking-secrets", "baz", false, true));
  }

  @Test
  public void secretsAreAppliedIfFound() throws IOException {
    HttpURLConnection conn = getConnection(URI.create("https://no.secrets.here"));
    Map<String, List<String>> properties = conn.getRequestProperties();
    // no secrets for this URI, just the user agent header
    assertThat(properties.size(), is(1));
    assertTrue(properties.containsKey("User-Agent"));

    conn = getConnection(URI.create("https://localhost"));
    properties = conn.getRequestProperties();
    assertThat(properties.size(), is(2));
    assertTrue(properties.containsKey("User-Agent"));
    assertThat(properties, hasEntry("secure", Lists.newArrayList("foo")));

    conn = getConnection(URI.create("https://sub.domain.localhost"));
    properties = conn.getRequestProperties();
    assertThat(properties.size(), is(2));
    assertTrue(properties.containsKey("User-Agent"));
    assertThat(properties, hasEntry("secureWithSubDomains", Lists.newArrayList("bar")));

    conn = getConnection(URI.create("http://localhost"));
    properties = conn.getRequestProperties();
    assertThat(properties.size(), is(2));
    assertTrue(properties.containsKey("User-Agent"));
    assertThat(properties, hasEntry("insecure", Lists.newArrayList("baz")));
  }

  @Test
  public void willLocalizeHttps() throws Exception {
    resource = of("https://" + HTTPS_TEST_URI + "/cpython-test/add.py");
    Path local = resource.ensureLocal(options).get();
    assertThat(Files.readAllLines(local).get(0), containsString("a simple cpython function used for test purposes"));
  }

  @Test
  public void willLocalizeHttpIfAllowed() throws Exception {
    resource = of("http://" + HTTPS_TEST_URI + "/cpython-test/add.py");
    assertThat(resource.ensureLocal(options), Matchers.failedResult(
        is(ResourceProblems.get().insecureNotAllowed(resource.getLocation()))
    ));
    options.setAllowInsecure(true);
    // GL1002 the following line is commented out because it will fail until the Http resource loader is smarted
    // up to handle the redirect.
    //local = resource.ensureLocal(options).get();
    //assertThat(Files.readAllLines(local).get(0), containsString("a simple cpython function used for test purposes"));
  }

  @Test
  public void missingResourcesAreNotFound() {
    resource = of("https://" + HTTPS_TEST_URI + "/cpython-test/missing-file.txt");
    RiskscapeIOException ex = assertThrows(RiskscapeIOException.class, () -> resource.getContentAsString());
    assertEquals(
        ResourceProblems.get().notFound(URI.create("https://" + HTTPS_TEST_URI + "/cpython-test/missing-file.txt")),
        ex.getProblem());
  }

  @Test
  public void fileExtensionsCanBeForced() throws Exception {
    resource = of("https://" + HTTPS_TEST_URI + "/cpython-test/add.py");
    Path local = resource.ensureLocal(options, "ini").get();
    assertTrue(Files.exists(local));
    assertThat(local.getFileName().toString(), equalTo("add.ini"));
  }

  @Test
  public void willNotLocalizeHttpIfNotAllowed() throws Exception {
    resource = of("http://" + HTTPS_TEST_URI + "/cpython-test/add.py");
    assertThat(resource.ensureLocal(options, "ini"), Matchers.failedResult(
        is(ResourceProblems.get().insecureNotAllowed(resource.getLocation()))
    ));
  }

  @Test
  public void unauthorizedGivesGoodErrors() throws Exception {
    when(mockConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_UNAUTHORIZED);

    resource = mockingSubject.load(URI.create("https://mocking/mock/mock"));
    assertThat(
      assertThrows(RiskscapeIOException.class, () -> resource.getContentAsString()).getProblem(),
      is(
          ResourceProblems.get().unauthorized(
              URI.create("https://mocking/mock/mock"),
              SecretProblems.get().noSecretsHint(Secrets.getUserHomeSecrets(engine))
          )
      )
    );

    resource = mockingSubject.load(URI.create("https://localhost/mock/mock"));
    assertThat(assertThrows(RiskscapeIOException.class, () -> resource.getContentAsString()).getProblem(),
      is(ResourceProblems.get().unauthorized(URI.create("https://localhost/mock/mock"),
              SecretProblems.get().secretsHint((HttpSecret)secrets.get("secure", engine.getProblemSink()))
          )
      )
    );
  }

  @Test
  public void forbiddenGivesGoodErrors() throws Exception {
    when(mockConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_FORBIDDEN);

    resource = mockingSubject.load(URI.create("https://mocking/mock/mock"));
    assertThat(
      assertThrows(RiskscapeIOException.class, () -> resource.getContentAsString()).getProblem(),
      is(
          ResourceProblems.get().forbidden(
              URI.create("https://mocking/mock/mock")
          )
      )
    );
  }

  HttpURLConnection getConnection(URI target) {
    try {
      return subject.getConnection(HttpSecret.getRequest(target, engine));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  Resource of(String uri) {
    return subject.load(URI.create(uri));
  }

  private HttpHeaderSecret secret(String id, String hostname, String headerValue,
      boolean allowSubDomains, boolean allowHttp) {
    HttpHeaderSecret secret = new HttpHeaderSecret();
    secret.setId(id);
    secret.setHostname(hostname);
    secret.setHeaderName(id);
    secret.setSecretHeaderValue(headerValue);
    secret.setAllowSubdomains(allowSubDomains);
    secret.setAllowHttp(allowHttp);

    return secret;
  }

}
