using System.Collections.Generic;
using System.Text.Json;

namespace Ablera.Serdica.Authority.Extensions;
public class JsonElementEqualityComparer : IEqualityComparer<JsonElement>
{
    public static JsonElementEqualityComparer Default = new JsonElementEqualityComparer();

    public bool Equals(JsonElement x, JsonElement y)
    {
        // if they’re not both JSON strings, fall back to raw-text compare
        if (x.ValueKind == JsonValueKind.String && y.ValueKind == JsonValueKind.String)
            return x.GetString() == y.GetString();

        // otherwise, compare their entire JSON text
        return x.GetRawText() == y.GetRawText();
    }

    public int GetHashCode(JsonElement obj)
    {
        // raw text is the canonical JSON including quotes, so it's stable for hashing
        return obj.GetRawText().GetHashCode();
    }
}

public static class DictionaryExtensions
{
    public static bool DictionaryEquals<TKey, TValue>(
        this IDictionary<TKey, TValue> a,
        IDictionary<TKey, TValue> b,
        IEqualityComparer<TValue>? valueComparer = null)
    {
        // same reference or both null?
        if (ReferenceEquals(a, b)) return true;
        // one null or different size?
        if (a is null || b is null || a.Count != b.Count) return false;

        valueComparer ??= EqualityComparer<TValue>.Default;

        foreach (var pair in a)
        {
            // key missing?
            if (!b.TryGetValue(pair.Key, out var bValue))
                return false;

            // value mismatch?
            if (!valueComparer.Equals(pair.Value, bValue))
                return false;
        }

        return true;
    }

}
