import { FREE_PLAN } from "./constants"; import { prisma } from "./db"; function getNextQuotaReset(from: Date = new Date()): Date { return new Date(from.getFullYear(), from.getMonth() + 1, 1); } export async function ensureQuotaReset(userId: string) { const user = await prisma.user.findUniqueOrThrow({ where: { id: userId } }); if (new Date() >= user.quotaResetAt) { return prisma.user.update({ where: { id: userId }, data: { videosUsed: 0, quotaResetAt: getNextQuotaReset(), }, }); } return user; } export async function getQuotaInfo(userId: string) { const user = await ensureQuotaReset(userId); const remaining = Math.max(0, FREE_PLAN.monthlyQuota - user.videosUsed); return { used: user.videosUsed, limit: FREE_PLAN.monthlyQuota, remaining, resetsAt: user.quotaResetAt.toISOString(), }; } export async function checkQuota(userId: string, requestedCount: number) { const info = await getQuotaInfo(userId); if (requestedCount > info.remaining) { return { ok: false as const, error: `Quota exceeded. You have ${info.remaining} videos remaining this month.`, ...info, }; } return { ok: true as const, ...info }; } export async function incrementQuota(userId: string, count: number) { await ensureQuotaReset(userId); await prisma.user.update({ where: { id: userId }, data: { videosUsed: { increment: count } }, }); } export function getInitialQuotaResetAt(): Date { return getNextQuotaReset(); }