using Metin2Launcher.Config;
using Xunit;

namespace Metin2Launcher.Tests;

public class LauncherSettingsTests : IDisposable
{
    private readonly string _tmp;

    public LauncherSettingsTests()
    {
        _tmp = Path.Combine(Path.GetTempPath(), "metin-settings-" + Guid.NewGuid());
        Directory.CreateDirectory(_tmp);
    }

    public void Dispose()
    {
        try { Directory.Delete(_tmp, recursive: true); } catch { }
    }

    [Fact]
    public void Defaults_when_file_missing()
    {
        var path = Path.Combine(_tmp, "missing.json");
        var s = LauncherSettings.Load(path);
        Assert.Equal("cs", s.Locale);
        Assert.False(s.DevMode);
        Assert.Null(s.ManifestUrlOverride);
    }

    [Fact]
    public void Save_then_load_round_trip()
    {
        var path = Path.Combine(_tmp, "s.json");
        var s = new LauncherSettings { Locale = "en", DevMode = true, ManifestUrlOverride = "https://example.test/m.json" };
        s.Save(path);

        var loaded = LauncherSettings.Load(path);
        Assert.Equal("en", loaded.Locale);
        Assert.True(loaded.DevMode);
        Assert.Equal("https://example.test/m.json", loaded.ManifestUrlOverride);
    }

    [Fact]
    public void Override_ignored_when_devmode_off()
    {
        var s = new LauncherSettings { DevMode = false, ManifestUrlOverride = "https://evil.test/m.json" };
        Assert.Equal(LauncherConfig.ManifestUrl, s.EffectiveManifestUrl());
        Assert.Equal(LauncherConfig.SignatureUrl, s.EffectiveSignatureUrl());
        Assert.Equal(LauncherConfig.BlobBaseUrl, s.EffectiveBlobBaseUrl());
    }

    [Fact]
    public void Override_used_when_devmode_on()
    {
        var s = new LauncherSettings { DevMode = true, ManifestUrlOverride = "https://example.test/m.json" };
        Assert.Equal("https://example.test/m.json", s.EffectiveManifestUrl());
        Assert.Equal("https://example.test/m.json.sig", s.EffectiveSignatureUrl());
        Assert.Equal("https://example.test/files", s.EffectiveBlobBaseUrl());
    }

    [Fact]
    public void Corrupt_file_falls_back_to_defaults()
    {
        var path = Path.Combine(_tmp, "bad.json");
        File.WriteAllText(path, "{not json");
        var s = LauncherSettings.Load(path);
        Assert.Equal("cs", s.Locale);
    }
}
