import "server-only";
import Stripe from "stripe";
import { prisma } from "@/lib/prisma";
import { decrypt } from "@/lib/crypto";

export async function getStripeSettings() {
  const settings = await prisma.settings.findUnique({ where: { id: "singleton" } });
  if (!settings?.stripeSecretKeyEnc) {
    return null;
  }
  return {
    secretKey: decrypt(settings.stripeSecretKeyEnc),
    publishableKey: settings.stripePublishableKey ?? "",
    webhookSecret: settings.stripeWebhookSecretEnc
      ? decrypt(settings.stripeWebhookSecretEnc)
      : null,
    notificationEmail: settings.notificationEmail ?? null,
  };
}

export async function getStripeClient(): Promise<Stripe> {
  const settings = await getStripeSettings();
  if (!settings) {
    throw new Error(
      "Stripe is not configured yet. An admin needs to add Stripe API keys in /admin/settings."
    );
  }
  return new Stripe(settings.secretKey);
}
