import { Request, Response, NextFunction } from "express";
import fetch from "node-fetch";

export const captchaMiddleware = async (
  req: Request,
  res: Response,
  next: NextFunction
): Promise<void> => {
  console.log("[Middleware] Captcha triggered on:", req.path);

  const captchaToken = req.body.captchaToken; // token from client
  if (!captchaToken) {
    res.status(400).json({ message: "Captcha token is missing" });
    return;
  }

  try {
    const secretKey = process.env.CLOUDFLARE_SECRET_KEY;
    if (!secretKey) {
      throw new Error(
        "Missing Cloudflare Turnstile secret key in env variables"
      );
    }

    // Verify token with Cloudflare Turnstile
    const response = await fetch(
      "https://challenges.cloudflare.com/turnstile/v0/siteverify",
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          secret: secretKey,
          response: captchaToken,
          remoteip: req.ip, // optional: track IP
        }),
      }
    );

    const data: any = await response.json();
    console.log("Captcha verification response:", data);

    if (!data.success) {
      res.status(400).json({
        message: "Captcha verification failed",
        errors: data["error-codes"] || [],
      });
      return;
    }

    // Captcha is valid → continue
    next();
  } catch (error: any) {
    console.error("Captcha middleware error:", error.message);
    res.status(500).json({ message: "Captcha verification error" });
  }
};
