import type { CaptchaPayload } from './captcha-types';

/**
 * Verify-gate for forms that submit directly to the Store API from the browser
 * (newsletter, review, registration). Call this with the <Captcha /> payload
 * before the Store API request; it throws with a user-facing message if the
 * CAPTCHA is invalid. Resolves silently when no CAPTCHA is active.
 */
export async function runCaptchaGate(payload: CaptchaPayload): Promise<void> {
  const res = await fetch('/api/captcha/verify', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    const data = await res.json().catch(() => ({}));
    throw new Error(data.error || 'Captcha verification failed. Please try again.');
  }
}
