export class QuotaExceededError extends Error {
    scope;
    constructor(scope) {
        super(scope === "user" ? "Daily user chapter quota exceeded." : "Global daily chapter quota exceeded.");
        this.scope = scope;
        this.name = "QuotaExceededError";
    }
}
export class StudioQuotaRuntime {
    options;
    userCounters = new Map();
    globalCounter;
    lastDate;
    constructor(options) {
        this.options = options;
        this.lastDate = this.currentDate();
        this.globalCounter = { date: this.lastDate, chapters: 0 };
    }
    get dailyChapterLimit() {
        return this.options.dailyChapterLimit;
    }
    get globalDailyChapterLimit() {
        return this.options.globalDailyChapterLimit;
    }
    ensureFreshDate() {
        const today = this.currentDate();
        if (today === this.lastDate)
            return false;
        this.lastDate = today;
        this.userCounters.clear();
        this.globalCounter = { date: today, chapters: 0 };
        this.options.onRollover?.();
        return true;
    }
    getUserUsage(userId) {
        return this.getUserCounter(userId).chapters;
    }
    getGlobalUsage() {
        this.ensureFreshDate();
        return this.globalCounter.chapters;
    }
    assertCanConsume(userId) {
        this.ensureFreshDate();
        if (this.getUserCounter(userId).chapters >= this.options.dailyChapterLimit) {
            throw new QuotaExceededError("user");
        }
        if (this.globalCounter.chapters >= this.options.globalDailyChapterLimit) {
            throw new QuotaExceededError("global");
        }
    }
    consumeChapter(userId) {
        this.assertCanConsume(userId);
        this.getUserCounter(userId).chapters += 1;
        this.globalCounter.chapters += 1;
    }
    getUserCounter(userId) {
        this.ensureFreshDate();
        const existing = this.userCounters.get(userId);
        if (existing)
            return existing;
        const counter = { date: this.lastDate, chapters: 0 };
        this.userCounters.set(userId, counter);
        return counter;
    }
    currentDate() {
        return this.options.today?.() ?? new Date().toISOString().slice(0, 10);
    }
}
//# sourceMappingURL=quota.js.map