import { openStore } from "@/lib/data/store";
import type { CaptchaSettings } from "@/lib/types";

const VERIFY_URLS = {
  recaptcha: "https://www.google.com/recaptcha/api/siteverify",
  turnstile: "https://challenges.cloudflare.com/turnstile/v0/siteverify",
  hcaptcha: "https://api.hcaptcha.com/siteverify",
} as const;

/**
 * Checks a captcha token with the provider.
 *
 * Passes when no captcha is configured, or when this action doesn't require
 * one — so callers can check unconditionally without knowing the settings.
 */
export async function verifyCaptcha(
  token: string | undefined,
  action: "signup" | "login" | "post" | "contact"
): Promise<{ ok: true } | { ok: false; error: string }> {
  const store = await openStore();
  const c = await store.small<CaptchaSettings>("captcha", {
    provider: "none",
  } as CaptchaSettings);

  if (c.provider === "none" || !c.secretKey) return { ok: true };
  if (!c.on[action]) return { ok: true };

  if (!token) {
    return { ok: false, error: "Please complete the captcha" };
  }

  try {
    const res = await fetch(VERIFY_URLS[c.provider], {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({ secret: c.secretKey, response: token }),
    });

    const body = await res.json();
    return body.success
      ? { ok: true }
      : { ok: false, error: "That captcha didn't check out — please try again" };
  } catch {
    // If the provider is unreachable, let people through rather than locking
    // everyone out of signing up.
    return { ok: true };
  }
}
