using ScadaLink.CLI;

namespace ScadaLink.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>SCADALINK_PASSWORD</c> / <c>SCADALINK_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("SCADALINK_PASSWORD");
        try
        {
            Environment.SetEnvironmentVariable("SCADALINK_PASSWORD", "s3cret");

            var config = CliConfig.Load();

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

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

            var config = CliConfig.Load();

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

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

            var config = CliConfig.Load();

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