import { prisma } from "@/lib/db"; import { periodKey } from "@/lib/utils"; import type { UsageMetric } from "@/lib/billing/plans"; export type OwnerType = "user" | "organization"; /** Increment a monthly usage counter for a billing subject. */ export async function incrementUsage( ownerId: string, ownerType: OwnerType, metric: UsageMetric, by = 1 ): Promise { const key = periodKey(new Date()); await prisma.usageRecord.upsert({ where: { ownerId_periodKey_metric: { ownerId, periodKey: key, metric } }, create: { ownerId, ownerType, periodKey: key, metric, count: by }, update: { count: { increment: by } }, }); } /** Current-period count for a single metric. */ export async function getUsage( ownerId: string, metric: UsageMetric, date = new Date() ): Promise { const rec = await prisma.usageRecord.findUnique({ where: { ownerId_periodKey_metric: { ownerId, periodKey: periodKey(date), metric } }, }); return rec?.count ?? 0; } /** Current-period counts for all metrics. */ export async function getUsageSummary( ownerId: string, date = new Date() ): Promise> { const rows = await prisma.usageRecord.findMany({ where: { ownerId, periodKey: periodKey(date) }, }); const summary: Record = { script: 0, audio: 0, art: 0, repurpose: 0 }; for (const row of rows) { if (row.metric in summary) summary[row.metric as UsageMetric] = row.count; } return summary; }