using ZB.MOM.WW.ScadaBridge.CLI;

namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;

[Collection("Environment")]
public class CliConfigTests
{
    [Fact]
    public void Load_DefaultFormat_IsJson()
    {
        var origUrl = Environment.GetEnvironmentVariable("SCADABRIDGE_MANAGEMENT_URL");
        var origFormat = Environment.GetEnvironmentVariable("SCADABRIDGE_FORMAT");

        try
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_MANAGEMENT_URL", null);
            Environment.SetEnvironmentVariable("SCADABRIDGE_FORMAT", null);

            var config = CliConfig.Load();

            // DefaultFormat is always "json" unless overridden by config file or env var
            Assert.Equal("json", config.DefaultFormat);
        }
        finally
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_MANAGEMENT_URL", origUrl);
            Environment.SetEnvironmentVariable("SCADABRIDGE_FORMAT", origFormat);
        }
    }

    [Fact]
    public void Load_ManagementUrl_FromEnvironment()
    {
        var orig = Environment.GetEnvironmentVariable("SCADABRIDGE_MANAGEMENT_URL");
        try
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_MANAGEMENT_URL", "http://central:5000");

            var config = CliConfig.Load();

            Assert.Equal("http://central:5000", config.ManagementUrl);
        }
        finally
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_MANAGEMENT_URL", orig);
        }
    }

    [Fact]
    public void Load_Format_FromEnvironment()
    {
        var orig = Environment.GetEnvironmentVariable("SCADABRIDGE_FORMAT");
        try
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_FORMAT", "table");

            var config = CliConfig.Load();

            Assert.Equal("table", config.DefaultFormat);
        }
        finally
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_FORMAT", orig);
        }
    }

    /// <summary>
    /// CLI-021 regression: a malformed ~/.scadabridge/config.json must NOT abort the
    /// CLI before any command runs — Load() must warn (to stderr) and return a
    /// usable default config so command-line overrides (--url, --username, etc.)
    /// and env vars can still take effect.
    /// </summary>
    [Fact]
    public void Load_MalformedConfigFile_DoesNotThrow_WarnsAndReturnsDefault()
    {
        var tempHome = Path.Combine(Path.GetTempPath(), "scadabridge-cli-test-" + Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(Path.Combine(tempHome, ".scadabridge"));
        File.WriteAllText(
            Path.Combine(tempHome, ".scadabridge", "config.json"),
            "{ this is not valid json :: ");

        var origHome = Environment.GetEnvironmentVariable("HOME");
        var origUserProfile = Environment.GetEnvironmentVariable("USERPROFILE");
        var origUrl = Environment.GetEnvironmentVariable("SCADABRIDGE_MANAGEMENT_URL");
        var origFormat = Environment.GetEnvironmentVariable("SCADABRIDGE_FORMAT");
        var origUser = Environment.GetEnvironmentVariable("SCADABRIDGE_USERNAME");
        var origPass = Environment.GetEnvironmentVariable("SCADABRIDGE_PASSWORD");
        var origStderr = Console.Error;
        try
        {
            Environment.SetEnvironmentVariable("HOME", tempHome);
            Environment.SetEnvironmentVariable("USERPROFILE", tempHome);
            Environment.SetEnvironmentVariable("SCADABRIDGE_MANAGEMENT_URL", null);
            Environment.SetEnvironmentVariable("SCADABRIDGE_FORMAT", null);
            Environment.SetEnvironmentVariable("SCADABRIDGE_USERNAME", null);
            Environment.SetEnvironmentVariable("SCADABRIDGE_PASSWORD", null);

            var stderrCapture = new StringWriter();
            Console.SetError(stderrCapture);

            // Must not throw.
            var config = CliConfig.Load();

            Assert.Equal("json", config.DefaultFormat);
            Assert.Null(config.ManagementUrl);
            var stderrText = stderrCapture.ToString();
            Assert.Contains("warning", stderrText, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("config.json", stderrText);
        }
        finally
        {
            Console.SetError(origStderr);
            Environment.SetEnvironmentVariable("HOME", origHome);
            Environment.SetEnvironmentVariable("USERPROFILE", origUserProfile);
            Environment.SetEnvironmentVariable("SCADABRIDGE_MANAGEMENT_URL", origUrl);
            Environment.SetEnvironmentVariable("SCADABRIDGE_FORMAT", origFormat);
            Environment.SetEnvironmentVariable("SCADABRIDGE_USERNAME", origUser);
            Environment.SetEnvironmentVariable("SCADABRIDGE_PASSWORD", origPass);
            try { Directory.Delete(tempHome, recursive: true); } catch { /* best-effort cleanup */ }
        }
    }
}
