using System.IO;
using System.Text.Json;
using SilverOS.Welcome.Core.Preconfig;
using Xunit;

public class PreconfigTests
{
    static string TempDir()
    {
        var d = Path.Combine(Path.GetTempPath(), "smpre-" + System.Guid.NewGuid().ToString("N"));
        Directory.CreateDirectory(d);
        return d;
    }

    const string Sample = """
    { "schemaVersion":1, "flavour":"developer",
      "bitlocker":{"enable":true,"pin":"246810"},
      "apps":{"useFlavourDefaults":true} }
    """;

    [Fact]
    public void Loads_flavour_and_pin()
    {
        var dir = TempDir();
        File.WriteAllText(Path.Combine(dir, "preconfig.json"), Sample);
        var p = new PreconfigStore(dir).Load();
        Assert.NotNull(p);
        Assert.Equal("developer", p!.Flavour);
        Assert.True(p.Bitlocker.Enable);
        Assert.Equal("246810", p.Bitlocker.Pin);
        Assert.True(p.Apps.UseFlavourDefaults);
    }

    [Fact]
    public void Missing_or_bad_file_returns_null_not_throw()
    {
        Assert.Null(new PreconfigStore(TempDir()).Load());            // missing
        var dir = TempDir();
        File.WriteAllText(Path.Combine(dir, "preconfig.json"), "{ not json");
        Assert.Null(new PreconfigStore(dir).Load());                 // corrupt
    }

    [Fact]
    public void ClearPin_rewrites_without_the_pin()
    {
        var dir = TempDir();
        File.WriteAllText(Path.Combine(dir, "preconfig.json"), Sample);
        var store = new PreconfigStore(dir);
        store.ClearPin();
        var reread = store.Load();
        Assert.True(string.IsNullOrEmpty(reread!.Bitlocker.Pin));
        Assert.Equal("developer", reread.Flavour); // rest preserved
    }

    [Fact]
    public void Configured_marker_roundtrips()
    {
        var dir = TempDir();
        var store = new PreconfigStore(dir);
        Assert.False(store.IsConfigured());
        store.MarkConfigured();
        Assert.True(store.IsConfigured());
    }
}
