/**
 * reCAPTCHA v3 Integration
 *
 * Protects forms from bot submissions and automated abuse
 * Uses invisible reCAPTCHA v3 with score-based validation
 */

export interface RecaptchaVerificationResult {
  success: boolean;
  score?: number;
  error?: string;
}

/**
 * Verify reCAPTCHA token with Google
 *
 * @param token - reCAPTCHA token from client
 * @param action - Action name for verification (e.g., 'demo_booking')
 * @returns Verification result with success status and score
 */
export async function verifyRecaptcha(
  token: string,
  action: string = 'demo_booking'
): Promise<RecaptchaVerificationResult> {
  const secretKey = process.env.RECAPTCHA_SECRET_KEY;

  if (!secretKey) {
    console.error('RECAPTCHA_SECRET_KEY not configured');
    // Fail open in development, fail closed in production
    if (process.env.NODE_ENV === 'production') {
      return {
        success: false,
        error: 'reCAPTCHA not configured',
      };
    }
    console.warn('reCAPTCHA bypassed in development mode');
    return { success: true, score: 1.0 };
  }

  if (!token) {
    return {
      success: false,
      error: 'reCAPTCHA token missing',
    };
  }

  try {
    const response = await fetch('https://www.google.com/recaptcha/api/siteverify', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: new URLSearchParams({
        secret: secretKey,
        response: token,
      }),
    });

    if (!response.ok) {
      return {
        success: false,
        error: 'reCAPTCHA verification failed',
      };
    }

    const data = await response.json();

    // Verify action matches
    if (data.action !== action) {
      return {
        success: false,
        error: 'reCAPTCHA action mismatch',
      };
    }

    // Check score threshold (0.5 is recommended for forms)
    const scoreThreshold = parseFloat(process.env.RECAPTCHA_SCORE_THRESHOLD || '0.5');

    if (data.success && data.score >= scoreThreshold) {
      return {
        success: true,
        score: data.score,
      };
    }

    return {
      success: false,
      score: data.score,
      error: `Low reCAPTCHA score: ${data.score}`,
    };
  } catch (error) {
    console.error('reCAPTCHA verification error:', error);
    return {
      success: false,
      error: 'reCAPTCHA verification error',
    };
  }
}

/**
 * Get reCAPTCHA site key for client-side
 */
export function getRecaptchaSiteKey(): string {
  return process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY || '';
}

/**
 * Check if reCAPTCHA is configured
 */
export function isRecaptchaConfigured(): boolean {
  return !!(
    process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY &&
    process.env.RECAPTCHA_SECRET_KEY
  );
}
