"use server";

import { cookies } from "next/headers";
import {
  CLAIM_COOKIE,
  firstPartyCookieOptions,
  INTENT_COOKIE,
  INTENT_MAX_AGE_SECONDS,
  openClaim,
  sealClaim,
  sealIntent,
} from "@/lib/claim";

/**
 * Put on this origin what the magic link's arrival will need to find, at the
 * one moment we know the visitor is really the one asking: the request itself.
 *
 * Two cookies, both first-party:
 *
 * - the claim, handed back by `POST /api/audit` and carried here in the URL,
 *   because the cookie that request set is third-party — dropped by Safari,
 *   partitioned by Firefox — and a claim missing at sign-in is a report the
 *   visitor paid an email for and never sees;
 * - the address asked for, sealed, so the session that later turns up can be
 *   checked against it instead of being taken at its word.
 *
 * A server action rather than the page: rendering cannot write a cookie, and
 * Next refuses an action invoked from another origin, which is exactly the
 * protection this one needs.
 */
export async function prepareClaim(email: string, sealedClaim: string | null): Promise<void> {
  const jar = await cookies();

  // Re-sealed from the token rather than echoed: what goes in the cookie is
  // then something we produced, in the shape the rest of the code expects.
  const token = openClaim(sealedClaim);
  if (token) jar.set(CLAIM_COOKIE, sealClaim(token), firstPartyCookieOptions());

  jar.set(INTENT_COOKIE, sealIntent(email), firstPartyCookieOptions(INTENT_MAX_AGE_SECONDS));
}
