#nullable enable
using Baya.Application.Contracts.Common;

namespace Baya.Application.Features.Verification;

/// <summary>
/// Cache-key scheme for verification reads. The step-type catalog is read-heavy reference data behind a
/// generation token (any admin step-type write bumps it, orphaning the whole namespace in one move — the
/// geo/catalog pattern). The public trust badge is cached per nurse with a short TTL and is explicitly
/// evicted on any state change that must reflect immediately (suspension, expiry re-gate, an admin decision).
/// </summary>
internal static class VerificationCache
{
    private const string VersionKey = "verification:step_types:version";

    public static readonly TimeSpan Ttl = TimeSpan.FromHours(1);

    /// <summary>Short TTL: a suspended/expired nurse is also evicted explicitly, so the badge is never
    /// stale-verified for long.</summary>
    public static readonly TimeSpan BadgeTtl = TimeSpan.FromSeconds(60);

    public static ValueTask<string> VersionAsync(ICacheService cache, CancellationToken cancellationToken)
        => cache.GetOrCreateAsync(VersionKey, _ => ValueTask.FromResult(NewToken()), null, cancellationToken);

    public static ValueTask InvalidateStepTypesAsync(ICacheService cache, CancellationToken cancellationToken)
        => cache.SetAsync(VersionKey, NewToken(), null, cancellationToken);

    public static string StepTypesKey(string version, bool includeInactive)
        => $"verification:{version}:step_types:{includeInactive}";

    public static string BadgeKey(long nurseId) => $"verification:badge:{nurseId}";

    public static ValueTask InvalidateBadgeAsync(ICacheService cache, long nurseId, CancellationToken cancellationToken)
        => cache.RemoveAsync(BadgeKey(nurseId), cancellationToken);

    private static string NewToken() => Guid.NewGuid().ToString("N");
}
