using Microsoft.Extensions.DependencyInjection;
using Tiku.Application.Security;
using Tiku.Application.Tenancy;
using Tiku.Infrastructure.Caching;
using ZiggyCreatures.Caching.Fusion;

namespace Tiku.Infrastructure.Security;

internal sealed class TenantFeatureCacheInvalidator(
    [FromKeyedServices(BusinessCachingServiceCollectionExtensions.CacheName)]
    IFusionCache cache,
    ITenantRuntimeCacheInvalidator runtimeCacheInvalidator) : ITenantFeatureCacheInvalidator
{
    public async Task InvalidateAsync(Guid tenantId, CancellationToken cancellationToken = default)
    {
        await runtimeCacheInvalidator.InvalidateAsync(tenantId, cancellationToken);
        await Task.WhenAll(
            cache.RemoveAsync(
                TenantFeatureSnapshotProvider.CacheKey(tenantId, FeatureAccessOperation.Read),
                token: cancellationToken).AsTask(),
            cache.RemoveAsync(
                TenantFeatureSnapshotProvider.CacheKey(tenantId, FeatureAccessOperation.Write),
                token: cancellationToken).AsTask());
    }
}
