import axios from 'axios';

/**
 * Verify Google reCAPTCHA v3 token
 * @param {string} token - The reCAPTCHA token from the frontend
 * @param {string} action - The action name (e.g., 'signup', 'contact')
 * @param {number} minScore - Minimum score threshold (0.0 - 1.0, default 0.5)
 * @returns {Promise<{success: boolean, score: number, action: string}>}
 */
export const verifyRecaptcha = async (token, action, minScore = 0.5) => {
  try {
    // Allow skipping reCAPTCHA in development if token is null/undefined
    if (!token) {
      if (process.env.NODE_ENV === 'development') {
        console.warn('⚠️ reCAPTCHA token is missing - allowing in development mode');
        return { success: true, score: 1.0, action };
      }
      throw new Error('reCAPTCHA token is missing');
    }

    const secretKey = process.env.RECAPTCHA_SECRET_KEY;
    
    if (!secretKey) {
      console.error('❌ RECAPTCHA_SECRET_KEY is not configured');
      if (process.env.NODE_ENV === 'development') {
        console.warn('⚠️ Allowing request without reCAPTCHA in development mode');
        return { success: true, score: 1.0, action };
      }
      throw new Error('reCAPTCHA is not configured on server');
    }

    // Make request to Google's reCAPTCHA verification endpoint
    const response = await axios.post(
      `https://www.google.com/recaptcha/api/siteverify`,
      null,
      {
        params: {
          secret: secretKey,
          response: token,
        },
      }
    );

    const { success, score, action: returnedAction } = response.data;

    console.log('🔐 reCAPTCHA verification result:', {
      success,
      score,
      action: returnedAction,
      expectedAction: action,
    });

    // Check if verification was successful
    if (!success) {
      throw new Error('reCAPTCHA verification failed');
    }

    // Check if the action matches
    if (returnedAction !== action) {
      console.warn(`⚠️ reCAPTCHA action mismatch. Expected: ${action}, Got: ${returnedAction}`);
    }

    // Check if score meets minimum threshold
    if (score < minScore) {
      console.warn(`⚠️ reCAPTCHA score too low: ${score} (minimum: ${minScore})`);
      throw new Error('reCAPTCHA score too low - possible bot activity');
    }

    return {
      success: true,
      score,
      action: returnedAction,
    };
  } catch (error) {
    console.error('❌ reCAPTCHA verification error:', error.message);
    throw error;
  }
};
