using System.Text.Json;
using ClaudeDo.Ui;
using Xunit;

namespace ClaudeDo.Ui.Tests;

public class AppSettingsTests
{
    private static string TempConfigPath() =>
        Path.Combine(Path.GetTempPath(), $"claudedo-uicfg-{Guid.NewGuid():N}.json");

    [Fact]
    public void Language_defaults_to_empty()
    {
        Assert.Equal("", new AppSettings().Language);
    }

    [Fact]
    public void Language_round_trips_through_json()
    {
        var json = JsonSerializer.Serialize(new AppSettings { Language = "de" });

        var back = JsonSerializer.Deserialize<AppSettings>(json,
            new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;

        Assert.Equal("de", back.Language);
    }

    [Fact]
    public void DiffPreferences_DefaultToUnifiedAndNoWrap()
    {
        var settings = new AppSettings();

        Assert.Equal("unified", settings.DiffViewMode);
        Assert.False(settings.DiffWrapLines);
    }

    [Fact]
    public void DiffPreferences_SurviveSaveAndLoad()
    {
        var path = TempConfigPath();
        try
        {
            new AppSettings { ConfigPath = path, DiffViewMode = "split", DiffWrapLines = true }.Save();

            var restored = AppSettings.Load(path);

            Assert.Equal("split", restored.DiffViewMode);
            Assert.True(restored.DiffWrapLines);
            Assert.Equal(path, restored.ConfigPath);
        }
        finally
        {
            if (File.Exists(path)) File.Delete(path);
        }
    }

    [Fact]
    public void ConfigPath_IsNotWrittenIntoTheConfigFile()
    {
        var path = TempConfigPath();
        try
        {
            new AppSettings { ConfigPath = path }.Save();

            Assert.DoesNotContain("ConfigPath", File.ReadAllText(path), StringComparison.OrdinalIgnoreCase);
        }
        finally
        {
            if (File.Exists(path)) File.Delete(path);
        }
    }

    [Fact]
    public void DiffPreferences_ReadFromCamelCasedConfig()
    {
        const string json = """{"diffViewMode":"split","diffWrapLines":true}""";

        var restored = JsonSerializer.Deserialize<AppSettings>(json,
            new JsonSerializerOptions { PropertyNameCaseInsensitive = true })!;

        Assert.Equal("split", restored.DiffViewMode);
        Assert.True(restored.DiffWrapLines);
    }
}
