/**
 * Credit gate service with caching.
 *
 * Checks whether the user has remaining credits (or an unlimited plan)
 * and caches the result for a configurable TTL to avoid hammering the API.
 *
 */
import { fetchCreditBalance } from '../../credits/shortcut-credits.js';
export class CreditGate {
    cachedResult = null;
    cachedAt = 0;
    ttlMs;
    constructor(ttlMs = 60_000) {
        this.ttlMs = ttlMs;
    }
    async check(accessToken) {
        if (this.cachedResult && Date.now() - this.cachedAt < this.ttlMs) {
            return this.cachedResult;
        }
        let balance;
        try {
            balance = await fetchCreditBalance(accessToken);
        }
        catch {
            return { hasCredits: true, creditsRemaining: 0, isUnlimited: false, hasTeamBilling: false };
        }
        if (balance === null) {
            return { hasCredits: true, creditsRemaining: 0, isUnlimited: false, hasTeamBilling: false };
        }
        const result = {
            hasCredits: balance.isUnlimited || balance.creditsRemaining > 0,
            creditsRemaining: balance.creditsRemaining,
            isUnlimited: balance.isUnlimited,
            hasTeamBilling: balance.hasTeamBilling
        };
        this.cachedResult = result;
        this.cachedAt = Date.now();
        return result;
    }
    /** Returns the cached result if still within TTL, null otherwise. */
    getCached() {
        if (this.cachedResult && Date.now() - this.cachedAt < this.ttlMs) {
            return this.cachedResult;
        }
        return null;
    }
    /** Populate the cache from an already-fetched balance (e.g. from polling). */
    populate(balance) {
        this.cachedResult = {
            hasCredits: balance.isUnlimited || balance.creditsRemaining > 0,
            creditsRemaining: balance.creditsRemaining,
            isUnlimited: balance.isUnlimited,
            hasTeamBilling: balance.hasTeamBilling
        };
        this.cachedAt = Date.now();
    }
    invalidate() {
        this.cachedResult = null;
        this.cachedAt = 0;
    }
}
//# sourceMappingURL=credit-gate.js.map