/**
 * Optional Cloudflare Turnstile verification when TURNSTILE_SECRET_KEY is set.
 * If unset, all checks pass (local dev).
 */
export async function verifyTurnstileToken(token: string | undefined, remoteIp: string): Promise<boolean> {
  const secret = process.env.TURNSTILE_SECRET_KEY?.trim();
  if (!secret) return true;
  if (!token?.trim()) return false;
  const body = new URLSearchParams({
    secret,
    response: token.trim(),
    ...(remoteIp ? { remoteip: remoteIp } : {}),
  });
  const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body,
  });
  const data = (await res.json()) as { success?: boolean };
  return data.success === true;
}

/** Require captcha only when starting a new signup session (no sessionId yet). */
export async function verifyTurnstileForNewSession(
  sessionId: string | null | undefined,
  captchaToken: string | undefined,
  remoteIp: string,
): Promise<boolean> {
  const secret = process.env.TURNSTILE_SECRET_KEY?.trim();
  if (!secret) return true;
  if (sessionId) return true;
  return verifyTurnstileToken(captchaToken, remoteIp);
}
