using System.Security.Cryptography;
using System.Text;

namespace Baya.Application.Common;

/// <summary>
/// Deterministic hash of a variant's answered option-set — the key behind the duplicate-listing filtered
/// unique index (<c>UNIQUE(nurse_id, service_category_id, option_set_hash)</c>). Because the option-set is
/// multi-row, a plain composite unique index can't express "same set of choices"; hashing the sorted
/// <c>(group_id, value_id)</c> pairs reduces it to one comparable column. Sorting makes the hash order-
/// independent; the same set of choices always yields the same 64-char hex hash. An empty option-set
/// (a category with no answered groups) hashes to a stable value, so two such variants still collide.
/// </summary>
public static class OptionSetHash
{
    public static string Compute(IEnumerable<(long GroupId, long ValueId)> pairs)
    {
        var canonical = string.Join(
            "|",
            pairs.OrderBy(p => p.GroupId).ThenBy(p => p.ValueId)
                 .Select(p => $"{p.GroupId}:{p.ValueId}"));

        var hash = SHA256.HashData(Encoding.UTF8.GetBytes(canonical));
        return Convert.ToHexString(hash).ToLowerInvariant();
    }
}
