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

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

import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.google.common.collect.ImmutableMap;

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

@SuppressWarnings("unchecked")
public class PostGISConnectionOptionsTest {

  Map<String, String> fakeEnv = ImmutableMap.of("PGPASSWORD", "secret");
  Map<String, String> emptyEnv = ImmutableMap.of();

  PostGISConnectionOptions options = new PostGISConnectionOptions();
  List<Problem> drainedWarnings = new ArrayList<>();

  @Test
  public void canParseURIAndGetPasswordFromEnv() {
    parseAndDrain("postgis://me@host/my-db", fakeEnv);
    assertThat(drainedWarnings, hasSize(0));

    assertThat(options.getHost(), is("host"));
    assertThat(options.getPort(), is(5432));
    assertThat(options.getDatabase(), is("my-db"));
    assertThat(options.getUser(), is("me"));
    assertThat(options.getPassword(), is("secret"));

    assertThat(options.toJdbcUri(), is("jdbc:postgresql://host:5432/my-db?user=me&password=secret"));
  }

  @Test
  public void canParseACompleteURIAndOverrideValues() {
    // set a complete uri
    options.setLocation(URI.create("postgis://bob@foo-host:1200/bar-db"));

    assertThat(options.getHost(), is("foo-host"));
    assertThat(options.getPort(), is(1200));
    assertThat(options.getDatabase(), is("bar-db"));
    assertThat(options.getUser(), is("bob"));
    assertThat(options.getPassword(), nullValue());

    assertThat(options.validate().getProblems(), empty());

    // now clear something and show that it's not valid any more
    options.setPassword("squirrel");
    options.setUser(null);
    assertThat(options.validate().getProblems(), contains(GeneralProblems.get().required("user")));
  }

  @Test
  public void canParseAnIncompleteURIAndOverrideValues() {
    // set a complete uri
    options.setLocation(URI.create("postgis://foo"));

    assertThat(options.getHost(), is("foo"));
    assertThat(options.getPort(), is(5432));
    assertThat(options.getDatabase(), nullValue());
    assertThat(options.getUser(), nullValue());
    assertThat(options.getPassword(), nullValue());

    assertThat(options.validate().getProblems(), not(empty()));

    // now set some values and show that it's now valid
    options.setDatabase("bar-database");
    options.setUser("baz-user");
    assertThat(options.validate().getProblems(), empty());
  }

  @Test
  public void warnsIfPasswordInLocation() {
    // the password in location has priority, but you do get a warning for having it there.
    parseAndDrain("postgis://me:my-secret@host/my-db", fakeEnv);
    assertThat(drainedWarnings, contains(
        PostGISProblems.get().passwordInClearText()
    ));

    assertThat(options.getHost(), is("host"));
    assertThat(options.getPort(), is(5432));
    assertThat(options.getDatabase(), is("my-db"));
    assertThat(options.getUser(), is("me"));
    assertThat(options.getPassword(), is("my-secret"));

    assertThat(options.toJdbcUri(), is("jdbc:postgresql://host:5432/my-db?user=me&password=my-secret"));

    // can return to a PostGIS location, but san password
    assertThat(options.toLocation(), is(URI.create("postgis://me@host:5432/my-db")));
  }

  @Test
  public void passwordInLocationMayContainColons() {
    // the password in location may contain colons, we only split on the first colon in userInfo
    parseAndDrain("postgis://me:my:secret:password@host/my-db", fakeEnv);
    assertThat(drainedWarnings, contains(
        PostGISProblems.get().passwordInClearText()
    ));

    assertThat(options.toJdbcUri(), is("jdbc:postgresql://host:5432/my-db?user=me&password=my:secret:password"));
  }

  @Test
  public void passwordIsNotRequired() {
    // the DB may be setup to not need a password
    parseAndDrain("postgis://me@host/my-db", emptyEnv);
    assertThat(drainedWarnings, hasSize(0));

    assertThat(options.toJdbcUri(), is("jdbc:postgresql://host:5432/my-db?user=me"));
  }

  @Test
  public void warningOnIgnoredQuery() {
    parseAndDrain("postgis://me@host/my-db?foo=bar&baz=bazza", fakeEnv);
    assertThat(drainedWarnings, contains(
        PostGISProblems.get().ignoredFromLocation("foo=bar&baz=bazza", "query")
    ));

    assertThat(options.toJdbcUri(), is("jdbc:postgresql://host:5432/my-db?user=me&password=secret"));
  }

  @Test
  public void warningOnIgnoredFragment() {
    parseAndDrain("postgis://me@host/my-db#ignored", fakeEnv);
    assertThat(drainedWarnings, contains(
        PostGISProblems.get().ignoredFromLocation("ignored", "fragment")
    ));

    assertThat(options.toJdbcUri(), is("jdbc:postgresql://host:5432/my-db?user=me&password=secret"));
  }

  @Test
  public void trailingSlashDoesNotMakeAnIgnoredWarning() {
    parseAndDrain("postgis://me@host/my-db/", fakeEnv);
    assertThat(drainedWarnings, hasSize(0));

    assertThat(options.toJdbcUri(), is("jdbc:postgresql://host:5432/my-db?user=me&password=secret"));
  }

  @Test
  public void errorIfLocationIncomplete() {
    assertThat(parse("postgis:bob", emptyEnv), Matchers.failedResult(
        is(PostGISProblems.get().invalidLocation(URI.create("postgis:bob")))
    ));

    assertThat(parse("postgis://bob", emptyEnv), Matchers.failedResult(
        is(GeneralProblems.get().required("user")),
        is(GeneralProblems.get().required("database"))
    ));
    assertThat(parse("postgis://bob/foo", emptyEnv), Matchers.failedResult(
        is(GeneralProblems.get().required("user"))
    ));

    assertThat(parse("postgis://foo@bob", emptyEnv), Matchers.failedResult(
        is(GeneralProblems.get().required("database"))
    ));
  }

  @Test
  public void errorIfAnAlphaPortIsSpecified() {
    // alpha characters in the port mess up the URI parsing
    assertThat(parse("postgis://me@host:port/db", fakeEnv), Matchers.failedResult(
        is(PostGISProblems.get().invalidLocation(URI.create("postgis://me@host:port/db")))
    ));
  }

  private PostGISConnectionOptions parseAndDrain(String uriString, Map<String, String> env) {
    this.drainedWarnings = parse(uriString, env).getProblems();
    return options;
  }

  private ResultOrProblems<PostGISConnectionOptions> parse(String uriString, Map<String, String> env) {
    options = new PostGISConnectionOptions();
    options.setEnvironment(env);
    options.setLocation(URI.create(uriString));
    return options.validate();
  }

}
