using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace RioJoy.Core.Overlay;

/// <summary>
/// Loads and saves an <see cref="OverlayTemplate"/> as a <c>regions.json</c> — the
/// cockpit cell geometry extracted from the source artwork
/// (docs/reference/customBackground/riojoy.xcf). Same JSON conventions as
/// <see cref="Profiles.ConfigStore"/> (indented, enums as strings, null-skipping).
/// </summary>
public static class OverlayTemplateStore
{
    private static readonly JsonSerializerSettings Options = new()
    {
        Formatting = Formatting.Indented,
        NullValueHandling = NullValueHandling.Ignore,
        Converters = { new StringEnumConverter() },
    };

    public static string Serialize(OverlayTemplate template)
    {
        if (template is null) throw new ArgumentNullException(nameof(template));
        return JsonConvert.SerializeObject(template, Options);
    }

    public static OverlayTemplate Deserialize(string json)
    {
        if (string.IsNullOrWhiteSpace(json)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(json));
        return JsonConvert.DeserializeObject<OverlayTemplate>(json, Options)
               ?? throw new JsonSerializationException("Overlay template JSON deserialized to null.");
    }

    public static void Save(OverlayTemplate template, string path)
    {
        if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(path));
        string? dir = Path.GetDirectoryName(Path.GetFullPath(path));
        if (!string.IsNullOrEmpty(dir))
            Directory.CreateDirectory(dir);
        File.WriteAllText(path, Serialize(template));
    }

    public static OverlayTemplate Load(string path)
    {
        if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Value cannot be null or whitespace.", nameof(path));
        return Deserialize(File.ReadAllText(path));
    }
}
