using RioJoy.Core.Calibration;
using RioJoy.Core.Profiles;
using Xunit;

namespace RioJoy.Core.Tests.Profiles;

public class ConfigStoreTests
{
    [Fact]
    public void RoundTrips_FullConfig()
    {
        var config = new AppConfig
        {
            DefaultRioComPort = "COM3",
            DefaultPlasmaComPort = "COM4",
            NativeGameExecutables = { "firestorm.exe", "redplanet.exe" },
            NeutralProfileName = "Desktop",
            Profiles =
            {
                new RioProfile
                {
                    Name = "Doom",
                    RioComPort = "COM5",
                    PlasmaGreeting = "DOOM",
                    Buttons = { [0] = 0x8049, [0x50] = 0x1009 },
                    Calibration = new AxisCalibrationConfig { InvertY = true, EnableZR = false },
                    MatchExecutables = { "doom.exe" },
                },
            },
        };

        string json = ConfigStore.Serialize(config);
        AppConfig back = ConfigStore.Deserialize(json);

        Assert.Equal("COM3", back.DefaultRioComPort);
        Assert.Equal(new[] { "firestorm.exe", "redplanet.exe" }, back.NativeGameExecutables);

        RioProfile p = Assert.Single(back.Profiles);
        Assert.Equal("Doom", p.Name);
        Assert.Equal("COM5", p.RioComPort);
        Assert.Equal(0x8049, p.Buttons[0]);
        Assert.Equal(0x1009, p.Buttons[0x50]);
        Assert.True(p.Calibration.InvertY);
        Assert.False(p.Calibration.EnableZR);
        Assert.Equal(new[] { "doom.exe" }, p.MatchExecutables);
    }

    [Fact]
    public void Load_MissingFile_ReturnsDefaults()
    {
        string path = Path.Combine(Path.GetTempPath(), $"riojoy-missing-{Guid.NewGuid():N}.json");
        AppConfig config = ConfigStore.Load(path);
        Assert.Empty(config.Profiles);
        Assert.Equal("COM1", config.DefaultRioComPort);
    }

    [Fact]
    public void Save_ThenLoad_File()
    {
        string path = Path.Combine(Path.GetTempPath(), $"riojoy-{Guid.NewGuid():N}", "config.json");
        try
        {
            var config = new AppConfig { DefaultRioComPort = "COM9" };
            ConfigStore.Save(config, path);
            Assert.True(File.Exists(path));
            Assert.Equal("COM9", ConfigStore.Load(path).DefaultRioComPort);
        }
        finally
        {
            string? dir = Path.GetDirectoryName(path);
            if (dir is not null && Directory.Exists(dir))
                Directory.Delete(dir, recursive: true);
        }
    }
}
