/**
 * Captcha configuration
 * Supports Turnstile, hCaptcha, and reCAPTCHA v2/v3
 */

export type CaptchaProvider = "turnstile" | "hcaptcha" | "recaptcha-v2" | "recaptcha-v3" | "none";

export interface CaptchaConfig {
	enabled: boolean;
	provider: CaptchaProvider;
	secretKey: string;
	bypassToken?: string;
	paintInterval?: number | undefined; // For paint captcha: require captcha every N paints (0 = always require)
}

export interface CaptchaVerificationPoints {
	login: CaptchaConfig;
	register: CaptchaConfig;
	googleOAuth: CaptchaConfig;
	paint: CaptchaConfig;
}

// Load environment variables with proper defaults
const createCaptchaConfig = (
	enabledEnv: string | undefined,
	provider: string | undefined,
	secretKey: string | undefined,
	bypassToken: string | undefined,
	paintInterval?: string | undefined
): CaptchaConfig => {
	const enabled = enabledEnv?.toLowerCase() === "true";
	const normalizedProvider = (provider?.toLowerCase() || "none") as CaptchaProvider;

	return {
		enabled,
		provider: normalizedProvider,
		secretKey: secretKey || "",
		bypassToken: bypassToken || "",
		paintInterval: paintInterval ? Number.parseInt(paintInterval, 10) : undefined
	};
};

// Captcha configuration for different verification points
export const captchaConfig: CaptchaVerificationPoints = {
	login: createCaptchaConfig(
		process.env["CAPTCHA_LOGIN_ENABLED"],
		process.env["CAPTCHA_LOGIN_PROVIDER"],
		process.env["CAPTCHA_LOGIN_SECRET"],
		process.env["CAPTCHA_LOGIN_BYPASS_TOKEN"]
	),
	register: createCaptchaConfig(
		process.env["CAPTCHA_REGISTER_ENABLED"],
		process.env["CAPTCHA_REGISTER_PROVIDER"],
		process.env["CAPTCHA_REGISTER_SECRET"],
		process.env["CAPTCHA_REGISTER_BYPASS_TOKEN"]
	),
	googleOAuth: createCaptchaConfig(
		process.env["CAPTCHA_GOOGLE_OAUTH_ENABLED"],
		process.env["CAPTCHA_GOOGLE_OAUTH_PROVIDER"],
		process.env["CAPTCHA_GOOGLE_OAUTH_SECRET"],
		process.env["CAPTCHA_GOOGLE_OAUTH_BYPASS_TOKEN"]
	),
	paint: createCaptchaConfig(
		process.env["CAPTCHA_PAINT_ENABLED"],
		process.env["CAPTCHA_PAINT_PROVIDER"],
		process.env["CAPTCHA_PAINT_SECRET"],
		process.env["CAPTCHA_PAINT_BYPASS_TOKEN"],
		process.env["CAPTCHA_PAINT_INTERVAL"]
	)
};

// Backward compatibility with old TURNSTILE_* environment variables
if (!captchaConfig.googleOAuth.secretKey && process.env["TURNSTILE_SECRET_KEY"]) {
	captchaConfig.googleOAuth = {
		enabled: true,
		provider: "turnstile",
		secretKey: process.env["TURNSTILE_SECRET_KEY"],
		bypassToken: process.env["TURNSTILE_BYPASS_TOKEN"] || ""
	};
}
