const VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverify";

type SiteverifyResponse = {
  success?: boolean;
  "error-codes"?: string[];
};

/**
 * Ask Cloudflare whether this token is one it issued, to this site, just now.
 *
 * A token is single-use and short-lived, which is what makes this worth a
 * round trip before anything else happens: it costs one request to Cloudflare
 * to avoid spawning a browser-less scraper's audit.
 *
 * The remote address is passed when we have it so Cloudflare can match the
 * token to the client that solved the challenge.
 */
export async function verifyTurnstile(token: string, remoteIp?: string): Promise<boolean> {
  const secret = process.env.TURNSTILE_SECRET_KEY;
  if (!secret) throw new Error("TURNSTILE_SECRET_KEY is not set — see .env.example");
  if (!token) return false;

  const body = new URLSearchParams({ secret, response: token });
  if (remoteIp && remoteIp !== "unknown") body.set("remoteip", remoteIp);

  try {
    const response = await fetch(VERIFY_URL, {
      method: "POST",
      body,
      // Cloudflare being slow must not hold a request open for a minute; a
      // failed verification is a 403, which is the safe direction to fail.
      signal: AbortSignal.timeout(5000),
    });
    if (!response.ok) return false;
    const result = (await response.json()) as SiteverifyResponse;
    return result.success === true;
  } catch {
    return false;
  }
}
