import 'server-only'

/** reCAPTCHA v3 is checked by our server; Supabase Auth does not accept v3 tokens. */
export async function verifyRecaptcha(token: string | null | undefined, action: string, hostname: string): Promise<{ ok: true } | { ok: false; error: string }> {
  const siteKey = process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY
  const secret = process.env.RECAPTCHA_SECRET_KEY
  if (!siteKey && !secret) return { ok: true }
  if (!siteKey || !secret) return { ok: false, error: 'Security verification is not configured. Please contact support.' }
  if (!token || token.length > 4096) return { ok: false, error: 'Security verification failed. Please try again.' }

  try {
    const body = new URLSearchParams({ secret, response: token })
    const response = await fetch('https://www.google.com/recaptcha/api/siteverify', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body,
      cache: 'no-store',
      signal: AbortSignal.timeout(5000),
    })
    if (!response.ok) throw new Error('Verification service unavailable')
    const result = await response.json() as { success?: boolean; score?: number; action?: string; hostname?: string }
    if (result.success && result.action === action && result.hostname === hostname && typeof result.score === 'number' && result.score >= 0.5) {
      return { ok: true }
    }
  } catch {
    // Fail closed when the verification service cannot be reached.
  }
  return { ok: false, error: 'Security verification failed. Please try again.' }
}

export function recaptchaHostname(requestHost: string | null): string {
  const configured = process.env.NEXT_PUBLIC_APP_URL
  if (configured) {
    try { return new URL(configured).hostname } catch { /* use the request host */ }
  }
  return (requestHost ?? '').split(':')[0]
}
