using System.Diagnostics;
using Metin2Launcher.Runtime;
using Xunit;

namespace Metin2Launcher.Tests;

public class EnvVarDeliveryTests
{
    private static RuntimeKey SampleKey() => new()
    {
        KeyId = "2026.04.14-1",
        MasterKeyHex = new string('a', 64),
        SignPubkeyHex = new string('b', 64),
    };

    [Fact]
    public void Apply_sets_expected_env_vars()
    {
        var psi = new ProcessStartInfo { FileName = "nothing" };
        new EnvVarKeyDelivery().Apply(psi, SampleKey());

        Assert.Equal("2026.04.14-1", psi.Environment[EnvVarKeyDelivery.KeyIdVar]);
        Assert.Equal(new string('a', 64), psi.Environment[EnvVarKeyDelivery.MasterKeyVar]);
        Assert.Equal(new string('b', 64), psi.Environment[EnvVarKeyDelivery.SignPubkeyVar]);
    }

    [Fact]
    public void Apply_does_not_leak_into_current_process()
    {
        var before = Environment.GetEnvironmentVariable(EnvVarKeyDelivery.MasterKeyVar);
        var psi = new ProcessStartInfo { FileName = "nothing" };
        new EnvVarKeyDelivery().Apply(psi, SampleKey());
        var after = Environment.GetEnvironmentVariable(EnvVarKeyDelivery.MasterKeyVar);
        Assert.Equal(before, after); // still unset (or whatever it was)
    }

    [Fact]
    public void Apply_overwrites_existing_values_on_psi()
    {
        var psi = new ProcessStartInfo { FileName = "nothing" };
        psi.Environment[EnvVarKeyDelivery.KeyIdVar] = "stale";
        new EnvVarKeyDelivery().Apply(psi, SampleKey());
        Assert.Equal("2026.04.14-1", psi.Environment[EnvVarKeyDelivery.KeyIdVar]);
    }

    [Fact]
    public void Apply_rejects_null_args()
    {
        var d = new EnvVarKeyDelivery();
        Assert.Throws<ArgumentNullException>(() => d.Apply(null!, SampleKey()));
        Assert.Throws<ArgumentNullException>(() => d.Apply(new ProcessStartInfo(), null!));
    }

    [Fact]
    public void SharedMemoryDelivery_is_stubbed()
    {
        var d = new SharedMemoryKeyDelivery();
        Assert.Equal("shared-memory", d.Name);
        Assert.Throws<NotSupportedException>(() =>
            d.Apply(new ProcessStartInfo(), SampleKey()));
    }

    [Fact]
    public void Delivery_name_is_env_var()
    {
        Assert.Equal("env-var", new EnvVarKeyDelivery().Name);
    }
}
