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

namespace RioJoy.Core.Profiles;

/// <summary>
/// Loads and saves <see cref="AppConfig"/> as JSON. Replaces the legacy
/// SimpleIni single-file config with a profile library (see docs/PLAN.md).
/// </summary>
public static class ConfigStore
{
    private static readonly JsonSerializerOptions Options = new()
    {
        WriteIndented = true,
        DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
        Converters = { new JsonStringEnumConverter() },
    };

    public static string Serialize(AppConfig config)
    {
        ArgumentNullException.ThrowIfNull(config);
        return JsonSerializer.Serialize(config, Options);
    }

    public static AppConfig Deserialize(string json)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(json);
        return JsonSerializer.Deserialize<AppConfig>(json, Options)
               ?? throw new JsonException("Config JSON deserialized to null.");
    }

    /// <summary>Save the config to <paramref name="path"/> (creating directories).</summary>
    public static void Save(AppConfig config, string path)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(path);
        string? dir = Path.GetDirectoryName(Path.GetFullPath(path));
        if (!string.IsNullOrEmpty(dir))
            Directory.CreateDirectory(dir);
        File.WriteAllText(path, Serialize(config));
    }

    /// <summary>
    /// Load the config from <paramref name="path"/>, or return a fresh default
    /// <see cref="AppConfig"/> if the file does not exist.
    /// </summary>
    public static AppConfig Load(string path)
    {
        ArgumentException.ThrowIfNullOrWhiteSpace(path);
        return File.Exists(path) ? Deserialize(File.ReadAllText(path)) : new AppConfig();
    }
}
