using System.Text.Json;

namespace VoiceCat.App.Models;

/// <summary>
/// Simple Load()/Save() over %AppData%\VoiceCat\servers.json. Tolerant of a missing/corrupt
/// file — that yields an empty list rather than throwing and blocking app startup.
/// </summary>
public static class ServerListStore
{
    private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };

    private static string AppDataDir => Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "VoiceCat");

    private static string ServersFilePath => Path.Combine(AppDataDir, "servers.json");

    /// <summary>Passed to VoiceCatClient's tofuStorePath — the C++ core owns the actual pin
    /// file format/logic (TofuStore), this just picks where it lives.</summary>
    public static string TofuStorePath => Path.Combine(AppDataDir, "tofu_pins.txt");

    public static List<SavedServer> Load()
    {
        try
        {
            if (!File.Exists(ServersFilePath)) return new List<SavedServer>();
            string json = File.ReadAllText(ServersFilePath);
            return JsonSerializer.Deserialize<List<SavedServer>>(json) ?? new List<SavedServer>();
        }
        catch
        {
            return new List<SavedServer>();
        }
    }

    public static void Save(List<SavedServer> servers)
    {
        Directory.CreateDirectory(AppDataDir);
        string json = JsonSerializer.Serialize(servers, JsonOptions);
        File.WriteAllText(ServersFilePath, json);
    }
}
