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

namespace Lumi.Companion.Core;

public sealed class SecureCredentialStore(string root)
{
    private readonly string _path = Path.Combine(root, "device.credential");
    private readonly string _installIdPath = Path.Combine(root, "install.id");
    public void Save(DeviceCredential credential)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(_path)!);
        var clear = JsonSerializer.SerializeToUtf8Bytes(credential, ProtocolV1.JsonOptions);
        var protectedBytes = ProtectedData.Protect(clear, "Lumi.Companion.Device.v1"u8.ToArray(), DataProtectionScope.CurrentUser);
        var temporary = $"{_path}.{Environment.ProcessId}.tmp";
        try { File.WriteAllBytes(temporary, protectedBytes); File.Move(temporary, _path, true); }
        finally { File.Delete(temporary); }
    }
    public DeviceCredential? Load()
    {
        if (!File.Exists(_path)) return null;
        var clear = ProtectedData.Unprotect(File.ReadAllBytes(_path), "Lumi.Companion.Device.v1"u8.ToArray(), DataProtectionScope.CurrentUser);
        return JsonSerializer.Deserialize<DeviceCredential>(clear, ProtocolV1.JsonOptions);
    }
    public void Remove() => File.Delete(_path);
    public string GetOrCreateInstallId()
    {
        Directory.CreateDirectory(Path.GetDirectoryName(_installIdPath)!);
        if (File.Exists(_installIdPath) && Guid.TryParse(File.ReadAllText(_installIdPath).Trim(), out var existing)) return existing.ToString();
        var created = Guid.NewGuid().ToString(); File.WriteAllText(_installIdPath, created); return created;
    }
}
