import Link from "next/link";

type SearchParams = Promise<{ session_id?: string }>;

async function getPaymentStatus(sessionId?: string) {
  const key = process.env.STRIPE_SECRET_KEY;
  if (!key || !sessionId || !/^cs_(test_|live_)?[A-Za-z0-9_]+$/.test(sessionId)) return null;
  try {
    const response = await fetch(`https://api.stripe.com/v1/checkout/sessions/${encodeURIComponent(sessionId)}`, {
      headers: { Authorization: `Bearer ${key}` },
      cache: "no-store",
    });
    if (!response.ok) return null;
    return (await response.json()) as { payment_status?: string; customer_details?: { email?: string } };
  } catch {
    return null;
  }
}

export default async function SuccessPage({ searchParams }: { searchParams: SearchParams }) {
  const { session_id: sessionId } = await searchParams;
  const session = await getPaymentStatus(sessionId);
  const paid = session?.payment_status === "paid";

  return (
    <main className="success-page">
      <header className="simple-header"><Link href="/"><img src="/logo.svg" alt="Beat My Car Quote" /></Link></header>
      <section className="success-card">
        <img src="/brand-icon.svg" alt="" />
        <p className="eyebrow-text">Request received</p>
        <h1>We’re on the search.</h1>
        <div className="success-status">{paid ? "Payment confirmed" : "Your checkout has been completed"}</div>
        <p>We’ll review your vehicle brief and send our recommendation within two business days{session?.customer_details?.email ? ` to ${session.customer_details.email}` : ""}.</p>
        <p>If we need one essential detail before beginning, we’ll contact you using the information provided.</p>
        <Link className="button" href="/">Return to the homepage</Link>
      </section>
    </main>
  );
}
