using ZB.MOM.WW.ScadaBridge.CLI;

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

/// <summary>
/// Regression tests for CLI-006 — credentials could only be supplied via the
/// <c>--password</c> command-line option, which leaks into process listings and
/// shell history. A <c>SCADABRIDGE_PASSWORD</c> / <c>SCADABRIDGE_USERNAME</c> environment
/// fallback gives CI/CD a safer alternative.
/// </summary>
[Collection("Environment")]
public class CredentialResolutionTests
{
    [Fact]
    public void Load_Password_FromEnvironment()
    {
        var orig = Environment.GetEnvironmentVariable("SCADABRIDGE_PASSWORD");
        try
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_PASSWORD", "s3cret");

            var config = CliConfig.Load();

            Assert.Equal("s3cret", config.Password);
        }
        finally
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_PASSWORD", orig);
        }
    }

    [Fact]
    public void Load_Username_FromEnvironment()
    {
        var orig = Environment.GetEnvironmentVariable("SCADABRIDGE_USERNAME");
        try
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_USERNAME", "ci-user");

            var config = CliConfig.Load();

            Assert.Equal("ci-user", config.Username);
        }
        finally
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_USERNAME", orig);
        }
    }

    [Fact]
    public void Load_NoCredentialEnvVars_LeavesCredentialsNull()
    {
        var origUser = Environment.GetEnvironmentVariable("SCADABRIDGE_USERNAME");
        var origPass = Environment.GetEnvironmentVariable("SCADABRIDGE_PASSWORD");
        try
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_USERNAME", null);
            Environment.SetEnvironmentVariable("SCADABRIDGE_PASSWORD", null);

            var config = CliConfig.Load();

            Assert.Null(config.Username);
            Assert.Null(config.Password);
        }
        finally
        {
            Environment.SetEnvironmentVariable("SCADABRIDGE_USERNAME", origUser);
            Environment.SetEnvironmentVariable("SCADABRIDGE_PASSWORD", origPass);
        }
    }
}
