using System.Text;

namespace SIGCM2.Infrastructure.Audit;

/// UDT-010 — opaque cursor for AuditEvent DESC pagination per design #D-6.
/// Format: base64url(`{OccurredAt:O}|{Id}`). Parse returns null on malformed input
/// (callers treat it as "start from the top" — fail-open on invalid cursor).
public static class AuditEventCursor
{
    public static string Encode(DateTime occurredAt, long id)
    {
        var raw = $"{occurredAt:O}|{id}";
        var bytes = Encoding.UTF8.GetBytes(raw);
        return Convert.ToBase64String(bytes);
    }

    public static (DateTime OccurredAt, long Id)? TryDecode(string? cursor)
    {
        if (string.IsNullOrWhiteSpace(cursor))
            return null;

        try
        {
            var bytes = Convert.FromBase64String(cursor);
            var raw = Encoding.UTF8.GetString(bytes);
            var pipe = raw.IndexOf('|');
            if (pipe <= 0 || pipe == raw.Length - 1)
                return null;

            var datePart = raw[..pipe];
            var idPart = raw[(pipe + 1)..];

            if (!DateTime.TryParse(datePart, null, System.Globalization.DateTimeStyles.RoundtripKind, out var occurredAt))
                return null;
            if (!long.TryParse(idPart, out var id))
                return null;

            return (occurredAt, id);
        }
        catch (FormatException)
        {
            return null;
        }
    }
}
