// const axios = require('axios');
// const RECAPTCHA_SECRET = '6LdiGHoqAAAAALFWyiAMq7Bt8Axw_hE0G8JZniIa';


// const verifyCaptcha = async (token, remoteIp) => {
//     console.log("token & ip", token, remoteIp);

//     if (!token) {
//         throw new Error("CAPTCHA verification failed. Missing token. Try again!");
//     }

//     try {
//         const response = await axios.post(`https://www.google.com/recaptcha/api/siteverify`, null, {
//             params: {
//                 secret: RECAPTCHA_SECRET, 
//                 response: token,
//                 remoteip: remoteIp
//             }
//         });

//         if (!response.data.success) {
//             console.error('CAPTCHA verification failed:', response.data);
//             throw new Error("CAPTCHA verification failed. Try again!");
//         }

//         // CAPTCHA verified successfully
//         return response.data;

//     } catch (error) {
//         console.error('CAPTCHA verification error:', error?.response?.data || error.message);
//         throw new Error('CAPTCHA verification error.');
//     }
// };

// module.exports = {




const axios = require("axios");

// Replace with your Cloudflare Turnstile secret key
const secretKey = "0x4AAAAAABvRHuhr3bCxEIop0RhwEJbA5Po";

/**
 * Verify Cloudflare Turnstile token
 * @param {string} token - The Turnstile token from Flutter
 * @returns {Promise<{success: boolean, message: string, errorCodes?: array}>}
 */
async function verifyCaptcha(token) {
  if (!token) {
    return {
      success: false,
      message: "No token received",
    };
  }

  try {
    const response = await axios.post(
      "https://challenges.cloudflare.com/turnstile/v0/siteverify",
      new URLSearchParams({
        secret: secretKey,
        response: token,
      }),
      {
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
      }
    );

    const result = response.data;
    console.log("Captcha verification result:", result); 
    if (!result.success) {
    console.log("Captcha error codes:", result["error-codes"]);
}

    if (result.success) {
      return {
        success: true,
        message: "Human verified ✅",
      };
    } else {
      return {
        success: false,
        message: "Verification failed ❌",
        errorCodes: result["error-codes"] || [],
      };
    }
  } catch (error) {
    console.error("Turnstile verification error:", error.message);
    return {
      success: false,
      message: "Internal server error",
    };
  }
}

module.exports = { verifyCaptcha };
