namespace ERPCore.Common.Http;

/// <summary>
/// Encodes the PostgreSQL xmin concurrency token (a <see cref="uint"/>) as an
/// opaque, quoted HTTP ETag and parses <c>If-Match</c> values back. Round-trips
/// via base64 so the value is stable and content-type agnostic
/// (docs/11-BACKEND-PHASE1.md §1.6).
/// </summary>
public static class ETag
{
    /// <summary>Quoted ETag string for a row-version token, e.g. <c>"0RsAAA=="</c>.</summary>
    public static string From(uint rowVersion)
        => "\"" + Convert.ToBase64String(BitConverter.GetBytes(rowVersion)) + "\"";

    /// <summary>Parse an <c>If-Match</c> header value (quoted, optionally weak) to a token.</summary>
    public static bool TryParse(string? ifMatch, out uint rowVersion)
    {
        rowVersion = 0;
        if (string.IsNullOrWhiteSpace(ifMatch)) return false;

        var v = ifMatch.Trim();
        if (v.StartsWith("W/", StringComparison.OrdinalIgnoreCase)) v = v[2..].Trim();
        v = v.Trim('"');

        try
        {
            var bytes = Convert.FromBase64String(v);
            if (bytes.Length != sizeof(uint)) return false;
            rowVersion = BitConverter.ToUInt32(bytes);
            return true;
        }
        catch (FormatException)
        {
            return false;
        }
    }
}
