using System.Security.Cryptography;
using System.Text.Json;
using Lumi.Companion.Protocol;

namespace Lumi.Companion.Core;

public sealed record StreamTestRecoveryState(
    string SessionId,
    string ServiceType,
    string ServiceSettingsJson,
    DateTimeOffset CreatedAt);

public sealed class StreamTestRecoveryStore(string root)
{
    private readonly string _path = Path.Combine(root, "stream-test.recovery");
    private static readonly byte[] Entropy = "Lumi.Companion.StreamTestRecovery.v1"u8.ToArray();

    public void Save(StreamTestRecoveryState state)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(_path)!);
        var clear = JsonSerializer.SerializeToUtf8Bytes(state, ProtocolV1.JsonOptions);
        var protectedBytes = ProtectedData.Protect(clear, Entropy, DataProtectionScope.CurrentUser);
        var temporary = $"{_path}.{Environment.ProcessId}.tmp";
        try
        {
            File.WriteAllBytes(temporary, protectedBytes);
            File.Move(temporary, _path, true);
        }
        finally
        {
            File.Delete(temporary);
            CryptographicOperations.ZeroMemory(clear);
        }
    }

    public StreamTestRecoveryState? Load()
    {
        if (!File.Exists(_path)) return null;
        var protectedBytes = File.ReadAllBytes(_path);
        var clear = ProtectedData.Unprotect(protectedBytes, Entropy, DataProtectionScope.CurrentUser);
        try { return JsonSerializer.Deserialize<StreamTestRecoveryState>(clear, ProtocolV1.JsonOptions); }
        finally { CryptographicOperations.ZeroMemory(clear); }
    }

    public bool Exists => File.Exists(_path);
    public void Remove() => File.Delete(_path);
}
