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

namespace Baya.Application.Features.Catalog;

/// <summary>
/// Cache-key scheme for the read-heavy public catalog lookups (categories + a category's option groups).
/// Every data key is namespaced by a generation token; any admin catalog mutation bumps the token, which
/// orphans all prior catalog entries in one move (they lapse by TTL). Mirrors the geo generation-token
/// scheme so cascade invalidation stays trivial and correct — deactivating a category or editing a group
/// instantly refreshes the whole namespace without enumerating child keys.
/// </summary>
internal static class CatalogCache
{
    private const string VersionKey = "catalog:version";

    // Catalog reference data changes rarely; a modest TTL bounds staleness even if a bump is ever missed.
    public static readonly TimeSpan Ttl = TimeSpan.FromHours(1);

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

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

    public static string CategoriesKey(string version) => $"catalog:{version}:categories";

    public static string OptionGroupsKey(string version, long categoryId) => $"catalog:{version}:groups:{categoryId}";

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