import Stripe from "stripe";
import { db } from "@/lib/db";

// ─── Read Stripe config from DB (site_settings) ───────────────────────────────

export async function getStripeConfig(): Promise<{
  mode: "live" | "sandbox";
  secretKey: string;
  publishableKey: string;
  webhookSecret: string;
}> {
  const keys = [
    "stripe_mode",
    "stripe_live_secret_key",
    "stripe_live_publishable_key",
    "stripe_live_webhook_secret",
    "stripe_sandbox_secret_key",
    "stripe_sandbox_publishable_key",
    "stripe_sandbox_webhook_secret",
  ];

  const settings = await db.siteSetting.findMany({ where: { key: { in: keys } } });
  const map = Object.fromEntries(settings.map((s) => [s.key, s.value ?? ""]));

  const mode = (map["stripe_mode"] ?? "sandbox") as "live" | "sandbox";

  return {
    mode,
    secretKey: mode === "live" ? map["stripe_live_secret_key"] : map["stripe_sandbox_secret_key"],
    publishableKey: mode === "live" ? map["stripe_live_publishable_key"] : map["stripe_sandbox_publishable_key"],
    webhookSecret: mode === "live" ? map["stripe_live_webhook_secret"] : map["stripe_sandbox_webhook_secret"],
  };
}

export async function getStripeClient(): Promise<Stripe> {
  const config = await getStripeConfig();
  if (!config.secretKey) {
    throw new Error("Stripe secret key not configured. Set it in Admin → Settings → Stripe.");
  }
  return new Stripe(config.secretKey, { apiVersion: "2026-05-27.dahlia" });
}

export async function getStripeMode(): Promise<"live" | "sandbox"> {
  const setting = await db.siteSetting.findUnique({ where: { key: "stripe_mode" } });
  return (setting?.value as "live" | "sandbox") ?? "sandbox";
}

// ─── Get the correct price ID for a package + currency + mode ────────────────

export function getPriceId(
  pkg: {
    stripePriceIdUsdLive: string | null;
    stripePriceIdNgnLive: string | null;
    stripePriceIdUsdSandbox: string | null;
    stripePriceIdNgnSandbox: string | null;
  },
  currency: "usd" | "ngn",
  mode: "live" | "sandbox"
): string | null {
  if (mode === "live") {
    return currency === "usd" ? pkg.stripePriceIdUsdLive : pkg.stripePriceIdNgnLive;
  }
  return currency === "usd" ? pkg.stripePriceIdUsdSandbox : pkg.stripePriceIdNgnSandbox;
}
