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

/// <summary>
/// Host-003: <c>appsettings.Central.json</c> no longer commits database connection
/// strings — they are externalised to environment variables. Tests that exercise the
/// full <c>Program</c> startup pipeline against the real SQL provider must therefore
/// supply the local dev connection string the way a deployment would: via an
/// environment variable (<c>Program</c>'s configuration builder calls
/// <c>AddEnvironmentVariables()</c>).
///
/// Also supplies <c>ScadaBridge__InboundApi__ApiKeyPepper</c> so the Central-role
/// StartupValidator preflight (added in 1fcc4f5) does not fail for tests that set
/// <c>DOTNET_ENVIRONMENT=Central</c> without an explicit pepper env var. Both vars
/// are restored on Dispose so tests stay isolated.
/// </summary>
internal sealed class CentralDbTestEnvironment : IDisposable
{
    // Local dev/test database — same credentials the infra docker-compose stack uses.
    // This is a test fixture value, not a committed production secret.
    private const string ConfigurationDb =
        "Server=localhost,1433;Database=ScadaBridgeConfig;User Id=scadabridge_app;Password=ScadaBridge_Dev1#;TrustServerCertificate=true";

    private const string ConfigKey = "ScadaBridge__Database__ConfigurationDb";

    // Test-only pepper — satisfies the ≥16-char StartupValidator requirement without
    // committing a real secret. The env-var name uses the double-underscore delimiter
    // so AddEnvironmentVariables() maps it to ScadaBridge:InboundApi:ApiKeyPepper.
    internal const string TestPepper = "test-pepper-01234567890";
    private const string PepperKey = "ScadaBridge__InboundApi__ApiKeyPepper";

    private readonly string? _previousConfig;
    private readonly string? _previousPepper;

    public CentralDbTestEnvironment()
    {
        _previousConfig = Environment.GetEnvironmentVariable(ConfigKey);
        Environment.SetEnvironmentVariable(ConfigKey, ConfigurationDb);

        _previousPepper = Environment.GetEnvironmentVariable(PepperKey);
        Environment.SetEnvironmentVariable(PepperKey, TestPepper);
    }

    public void Dispose()
    {
        Environment.SetEnvironmentVariable(ConfigKey, _previousConfig);
        Environment.SetEnvironmentVariable(PepperKey, _previousPepper);
    }
}
