using System.Text.Json;

namespace RolemasterDb.App.Features;

public sealed record CriticalCellEditorSnapshot(
    int Version,
    bool IsDescriptionOverridden,
    bool IsRawAffixTextOverridden,
    bool AreEffectsOverridden,
    bool AreBranchesOverridden,
    IReadOnlyList<CriticalEffectEditorItem> Effects,
    IReadOnlyList<CriticalBranchEditorItem> Branches,
    string? QuickParseInput)
{
    private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);

    public static CriticalCellEditorSnapshot FromRequest(CriticalCellUpdateRequest request) =>
        new(
            1,
            request.IsDescriptionOverridden,
            request.IsRawAffixTextOverridden,
            request.AreEffectsOverridden,
            request.AreBranchesOverridden,
            request.Effects,
            request.Branches,
            request.QuickParseInput);

    public string ToJson() =>
        JsonSerializer.Serialize(this, JsonOptions);

    public static bool TryParse(string json, out CriticalCellEditorSnapshot? snapshot)
    {
        snapshot = null;
        if (string.IsNullOrWhiteSpace(json))
        {
            return false;
        }

        try
        {
            using var document = JsonDocument.Parse(json);
            if (!document.RootElement.TryGetProperty("version", out var versionElement) ||
                versionElement.ValueKind != JsonValueKind.Number ||
                versionElement.GetInt32() != 1)
            {
                return false;
            }

            snapshot = JsonSerializer.Deserialize<CriticalCellEditorSnapshot>(json, JsonOptions);
            return snapshot is not null;
        }
        catch (JsonException)
        {
            return false;
        }
    }
}
