import { eq } from "drizzle-orm";
import { db } from "@db/client";
import { customers } from "@db/schema";
import { verifyUnsubscribeSignature } from "@/lib/campaign-optout";
import UnsubscribeForm from "./unsubscribe-form";

export const metadata = { title: "Unsubscribe" };

// Public, unauthenticated -- reached only via the signed link in a campaign
// email (src/lib/campaign-optout.ts buildUnsubscribeUrl).
export default async function UnsubscribePage({
  searchParams,
}: {
  searchParams: Promise<{ c?: string; s?: string }>;
}) {
  const { c: customerId, s: signature } = await searchParams;
  const valid = Boolean(customerId && signature && verifyUnsubscribeSignature(customerId, signature));

  let email: string | null = null;
  let alreadyOptedOut = false;
  if (valid && customerId) {
    const [row] = await db.select({ email: customers.email, emailOptIn: customers.emailOptIn }).from(customers).where(eq(customers.id, customerId)).limit(1);
    email = row?.email ?? null;
    alreadyOptedOut = row ? !row.emailOptIn : false;
  }

  return (
    <div className="min-h-screen bg-bg text-ink flex items-center justify-center px-4">
      <div className="max-w-sm w-full text-center">
        {!valid || !email ? (
          <>
            <h1 className="text-xl font-bold text-white mb-2">Invalid link</h1>
            <p className="text-muted">
              This unsubscribe link is invalid or has expired. Contact the organizer directly if you
              no longer want to hear from them.
            </p>
          </>
        ) : alreadyOptedOut ? (
          <>
            <h1 className="text-xl font-bold text-white mb-2">Already unsubscribed</h1>
            <p className="text-muted">{email} won&apos;t receive any more campaign emails.</p>
          </>
        ) : (
          <>
            <h1 className="text-xl font-bold text-white mb-2">Unsubscribe</h1>
            <p className="text-muted mb-6">
              Stop sending campaign emails to <span className="text-ink">{email}</span>?
            </p>
            <UnsubscribeForm customerId={customerId!} signature={signature!} />
          </>
        )}
      </div>
    </div>
  );
}
