import { db } from "@/lib/db";
import { auth } from "@/auth";
import CheckoutClient from "./CheckoutClient";

export const metadata = { title: "Checkout" };

async function getStripePk(): Promise<string> {
  try {
    const rows = await db.siteSetting.findMany({
      where: { key: { in: ["stripe_mode", "stripe_live_publishable_key", "stripe_sandbox_publishable_key"] } },
    });
    const get = (k: string) => rows.find(r => r.key === k)?.value ?? "";
    const mode = get("stripe_mode") === "live" ? "live" : "sandbox";
    const pk = mode === "live" ? get("stripe_live_publishable_key") : get("stripe_sandbox_publishable_key");
    
    // Check if key starts with pk_ (publishable key) - if it starts with sk_, it's wrong
    if (pk && !pk.startsWith("pk_")) {
      console.error("Stripe publishable key is invalid - appears to be a secret key");
      return "";
    }
    
    return pk;
  } catch (e) {
    console.error("Error loading Stripe key:", e);
    return "";
  }
}

export default async function CheckoutPage() {
  const stripePk = await getStripePk();
  const session = await auth();
  
  let savedShipping = null;
  if (session?.user?.id) {
    const user = await db.user.findUnique({
      where: { id: session.user.id },
      select: {
        shippingAddress: true,
        shippingCity: true,
        shippingState: true,
        shippingZip: true,
        shippingCountry: true,
      },
    });
    if (user) {
      savedShipping = {
        address: user.shippingAddress || "",
        city: user.shippingCity || "",
        state: user.shippingState || "",
        zip: user.shippingZip || "",
        country: user.shippingCountry || "Malaysia",
      };
    }
  }
  
  return <CheckoutClient stripePk={stripePk} savedShipping={savedShipping} />;
}
