using System.Text.Json;

namespace SilverOS.Welcome.Core.Preconfig;

public sealed class PreconfigStore(string dir) : IPreconfigStore
{
    private string File_ => Path.Combine(dir, "preconfig.json");
    private string Marker => Path.Combine(dir, "configured");

    public Preconfig? Load()
    {
        try
        {
            if (!File.Exists(File_)) return null;
            return JsonSerializer.Deserialize<Preconfig>(File.ReadAllText(File_), Preconfig.JsonOptions);
        }
        catch (JsonException) { return null; }   // fail-open
    }

    public void ClearPin()
    {
        var p = Load();
        if (p is null) return;
        var stripped = p with { Bitlocker = p.Bitlocker with { Pin = null } };
        File.WriteAllText(File_, JsonSerializer.Serialize(stripped, Preconfig.JsonOptions));
    }

    public bool IsConfigured() => File.Exists(Marker);
    public void MarkConfigured() { Directory.CreateDirectory(dir); File.WriteAllText(Marker, "1"); }
}
