import { env } from "../config/env.js";

interface TurnstileVerifyResponse {
  success: boolean;
  "error-codes"?: string[];
}

export function isTurnstileEnabled(): boolean {
  return env.TURNSTILE_SECRET_KEY.trim().length > 0;
}

export async function verifyTurnstileToken(input: {
  token: string;
  ip?: string | null;
}): Promise<boolean> {
  if (!isTurnstileEnabled()) return true;
  if (!input.token.trim()) return false;

  const body = new URLSearchParams({
    secret: env.TURNSTILE_SECRET_KEY,
    response: input.token.trim(),
  });

  if (input.ip?.trim()) {
    body.set("remoteip", input.ip.trim());
  }

  const res = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body,
  });

  if (!res.ok) return false;

  const payload = await res.json() as TurnstileVerifyResponse;
  return payload.success === true;
}
