/*
 * 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 nz.org.riskscape.engine.cli.BaseCliIntegrationTest.*;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.IOException;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import com.google.common.collect.ImmutableMap;

import nz.org.riskscape.engine.cli.BaseCliIntegrationTest2;
import nz.org.riskscape.engine.cli.CliIntegrationTest;
import nz.org.riskscape.engine.cli.CommandResult;
import nz.org.riskscape.engine.cli.PostgisIntegrationTestRunner;
import nz.org.riskscape.engine.types.Nullable;
import nz.org.riskscape.engine.types.Struct;
import nz.org.riskscape.test.SkipTestOnWindows;

@RunWith(PostgisIntegrationTestRunner.class)
@Category({CliIntegrationTest.class, PostGISIntegrationTestMarker.class})
public class RM351_Postgis_Via_Geotools extends BaseCliIntegrationTest2 {

  Struct stationType = Struct.of("name", Nullable.TEXT);
  Struct outputType = Struct.of("output", stationType);

  @Test
  @Category(SkipTestOnWindows.class)
  public void canUseRelationFromPostgisWithPGPASSWORD() throws Exception {
    CommandResult result = runner.execute(defaultCommand()
        .option("--project", homeDir().resolve("project.ini"))
        .subcommands("model", "run", "rail-stations")
        .option("--output", "output")
        .option("--replace")
        .environmentVariable("PGPASSWORD", "riskscape")
    );
    assertThat(result, exitsWith(0));
    assertRailOutput();
    // no warnings or errors here
    assertThat(result.stderr, hasSize(0));
  }

  @Test
  @Category(SkipTestOnWindows.class)
  public void canUseRelationFromPostgisWarningPasswordInLocation() throws Exception {
    CommandResult result = runner.execute(defaultCommand()
        .option("--project", homeDir().resolve("project.ini"))
        .subcommands("model", "run", "rail-stations")
        .option("--parameter=input='nz-rail-stations-password-in-location'")
        .option("--output", "output")
        .option("--replace")
        .environmentVariable("PGPASSWORD", "riskscape")
    );
    assertThat(result, exitsWith(0));
    assertRailOutput();
    hasInStderr("Supplying postgis passwords in clear text is insecure");
  }

  @Test
  @Category(SkipTestOnWindows.class)
  public void canUseRelationFromPostgisWarningPasswordInParam() throws Exception {
    CommandResult result = runner.execute(defaultCommand()
        .option("--project", homeDir().resolve("project.ini"))
        .subcommands("model", "run", "rail-stations")
        .option("--parameter=input='nz-rail-stations-password-in-param'")
        .option("--output", "output")
        .option("--replace")
        .environmentVariable("PGPASSWORD", "riskscape")
    );
    assertThat(result, exitsWith(0));
    assertRailOutput();
    // no warnings or errors here
    hasInStderr("Supplying postgis passwords in clear text is insecure");
  }

  @Test
  @Category(SkipTestOnWindows.class)
  public void connectionFailureHasGoodFailureMessage() throws Exception {
    CommandResult result = runner.execute(defaultCommand()
        .option("--project", homeDir().resolve("project.ini"))
        .subcommands("model", "run", "rail-stations")
        .option("--parameter=input='postgis://fake-user@nowhere:5432/bogus'")
        .option("--output", "output")
        .option("--replace")
        .environmentVariable("PGPASSWORD", "riskscape")
    );
    assertThat(result, exitsWith(1));
    assertThat(result.stderr, hasItem(containsString("Could not connect to postgis://fake-user@nowhere:5432/bogus")));
  }

  private void assertRailOutput() throws IOException {

    Map<String, List<String>> expected = ImmutableMap.of(
        "6082054", Arrays.asList("Greenlane Station", "POINT (-36.88965260770787 174.79744423074914)"),
        "6082051", Arrays.asList("Penrose Station", "POINT (-36.91012202505844 174.8157244628168)"),
        "6082053", Arrays.asList("Ellerslie Station", "POINT (-36.898725475187774 174.80824125198643)")
    );
    Path outputDir = environment().localSourceTree.resolve("output");
    assertTrue(outputDir.toFile().isDirectory());
    assertHasRecords(expected, outputDir.resolve("output.csv"), "t50_fid", "name", "geom");
  }
}
