import { redirect } from "next/navigation";
import { db } from "@/lib/db";
import { payments, tips } from "@/lib/db/schema";
import { eq } from "drizzle-orm";
import { confirmEmbeddedPayment } from "@/lib/confirmEmbeddedPayment";
import PaymentSuccessCard from "@/components/PaymentSuccessCard";

export const dynamic = "force-dynamic";

export default async function CheckoutSuccessPage({
  searchParams,
}: {
  searchParams: Promise<Record<string, string | undefined>>;
}) {
  const params = await searchParams;
  const paymentId = params.paymentId;
  if (!paymentId) redirect("/my-library");

  const isTip = paymentId.startsWith("tip_");
  const record = isTip
    ? (await db.select().from(tips).where(eq(tips.id, paymentId)))[0]
    : (await db.select().from(payments).where(eq(payments.id, paymentId)))[0];

  // Guests (no account) can land here for a tip — fall back to home rather
  // than My Library, which they can't access without logging in.
  if (!record) redirect(isTip ? "/tips" : "/my-library");

  // Shipping fields (if any) were appended to this return URL as ship_*
  // params before the redirect, since sessionStorage isn't reachable from a
  // server component.
  const shipping = {
    name: params.ship_name,
    addressLine1: params.ship_addressLine1,
    addressLine2: params.ship_addressLine2,
    city: params.ship_city,
    state: params.ship_state,
    postalCode: params.ship_postalCode,
    country: params.ship_country,
  };

  // Same server-side confirm the in-page flow uses — don't rely on the
  // webhook having already landed by the time this page loads.
  const result = await confirmEmbeddedPayment(paymentId, record.userId, shipping).catch(() => null);
  const isPaid = result?.ok && (result.status === "paid" || result.status === "active");

  return (
    <div className="py-8">
      <PaymentSuccessCard
        paymentId={paymentId}
        isSubscription={!isTip && (record as any).type === "subscription"}
        isTip={isTip}
        amount={record.amount}
        email={isTip ? (record as any).email : undefined}
        loggedIn={!!record.userId}
      />
      {!isPaid && (
        <p className="text-center text-xs text-neutral-500 mt-4">
          Finishing up — this can take a moment. Your invoice will be ready shortly.
        </p>
      )}
    </div>
  );
}
