using System.Text.Json;

namespace Flo.Installer.Provisioning;

internal sealed class SecretsStore(string path)
{
    public bool Exists() => File.Exists(path);

    public IReadOnlyDictionary<string, string> Load()
        => JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllBytes(path))
           ?? throw new InvalidOperationException($"Malformed secrets file: {path}");

    public void Save(IReadOnlyDictionary<string, string> secrets)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(path)!);
        File.WriteAllText(path, JsonSerializer.Serialize(secrets, new JsonSerializerOptions { WriteIndented = true }));
        RestrictPermissions(path);
    }

    // Phase 5 will swap this for DPAPI on Windows and real ACLs; Linux keeps the file-mode approach.
    private static void RestrictPermissions(string path)
    {
        if (OperatingSystem.IsLinux() || OperatingSystem.IsMacOS())
            File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
    }
}
