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

// Skips verification (returns success) when TURNSTILE_SECRET_KEY isn't set,
// same graceful-degradation pattern as the SMTP-not-configured checks in
// src/lib/mail.ts — forms keep working before a Cloudflare account exists,
// rather than hard-blocking every submission.
export async function verifyTurnstileToken(token: string | null, ip: string) {
  const secret = process.env.TURNSTILE_SECRET_KEY;
  if (!secret) return { success: true as const };

  if (!token) return { success: false as const };

  try {
    const res = await fetch(VERIFY_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: new URLSearchParams({ secret, response: token, remoteip: ip }),
    });
    const data = (await res.json()) as { success: boolean };
    return { success: data.success };
  } catch {
    return { success: false as const };
  }
}
