namespace Tiku.Application.Security;

public static class FeatureQuotaConsumptionExtensions
{
    public static async Task<bool> ConsumeQuotaIfConfiguredAsync(
        this IFeatureAccessService featureAccessService,
        Guid tenantId,
        string metricCode,
        long amount = 1,
        CancellationToken cancellationToken = default)
    {
        var configured = (await featureAccessService.GetQuotaSummaryAsync(tenantId, cancellationToken))
            .Any(item => string.Equals(item.MetricCode, metricCode, StringComparison.Ordinal));
        if (!configured) return false;

        if (!await featureAccessService.TryConsumeQuotaAsync(tenantId, metricCode, amount, cancellationToken))
            throw new FeatureAccessException("The tenant feature quota has been exhausted.", "feature_quota_exhausted");

        return true;
    }
}