import asyncHandler from '../utils/asyncHandler.js';
import ApiError from '../utils/ApiError.js';
import { env } from '../config/env.js';

const VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';


export const verifyRecaptcha = asyncHandler(async (req, _res, next) => {
  if (!env.recaptchaSecret) return next();

  const token = req.body?.recaptchaToken || req.body?.['g-recaptcha-response'];
  if (!token) throw ApiError.badRequest('Please complete the "I\'m not a robot" check.');

  const params = new URLSearchParams({ secret: env.recaptchaSecret, response: token });
  if (req.ip) params.append('remoteip', req.ip);

  let result;
  try {
    const resp = await fetch(VERIFY_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: params.toString(),
    });
    result = await resp.json();
  } catch {
    throw ApiError.badRequest('Could not verify the captcha. Please try again.');
  }

  if (!result.success) {
    throw ApiError.badRequest('Captcha verification failed. Please try again.');
  }

  next();
});
