import type { BillingAdapter } from "@/lib/billing/adapters";
import { prisma } from "./client.example";

export const prismaBillingAdapter: BillingAdapter = {
  async getSubscription(userId) {
    return prisma.subscription.findUnique({
      where: { userId },
    });
  },

  async upsertSubscription(record) {
    return prisma.subscription.upsert({
      where: {
        userId: record.userId,
      },
      create: record,
      update: record,
    });
  },

  async getUsage(
    userId,
    key,
    period
  ) {
    const usage =
      await prisma.usageEvent.findUnique({
        where: {
          userId_key_period: {
            userId,
            key,
            period,
          },
        },
      });

    return usage?.count ?? 0;
  },

  async incrementUsage(
    userId,
    key,
    period,
    amount
  ) {
    const usage =
      await prisma.usageEvent.upsert({
        where: {
          userId_key_period: {
            userId,
            key,
            period,
          },
        },
        create: {
          userId,
          key,
          period,
          count: amount,
        },
        update: {
          count: {
            increment: amount,
          },
        },
      });

    return usage.count;
  },
};
