using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace NexusShell.Services.Identity;

internal static class NexusIdentityStorage
{
    internal static readonly JsonSerializerOptions JsonOptions = new()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        WriteIndented = true,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) },
    };

    public static string IdentityDirectory =>
        Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
            "NinjaNexus",
            "identity");

    public static string OrganizationPath => Path.Combine(IdentityDirectory, "organization.json");
    public static string UserPath => Path.Combine(IdentityDirectory, "user.json");
    public static string DevicePath => Path.Combine(IdentityDirectory, "device.json");
    public static string TrustPath => Path.Combine(IdentityDirectory, "trust.json");

    public static void EnsureDirectory() => Directory.CreateDirectory(IdentityDirectory);

    public static T? Load<T>(string path) where T : class
    {
        if (!File.Exists(path))
        {
            return null;
        }

        try
        {
            var json = File.ReadAllText(path);
            return JsonSerializer.Deserialize<T>(json, JsonOptions);
        }
        catch
        {
            return null;
        }
    }

    public static void Save<T>(string path, T value)
    {
        EnsureDirectory();
        var json = JsonSerializer.Serialize(value, JsonOptions);
        File.WriteAllText(path, json);
    }
}
