import axios from "axios";
import BadDataException from "../../Types/Exception/BadDataException";
import logger from "./Logger";
import { CaptchaEnabled, CaptchaSecretKey } from "../EnvironmentConfig";
const REQUEST_TIMEOUT_MS = 5000;
const GENERIC_ERROR_MESSAGE = "Captcha verification failed. Please try again.";
class CaptchaUtil {
    static isCaptchaEnabled() {
        return CaptchaEnabled && Boolean(CaptchaSecretKey);
    }
    static async verifyCaptcha(options) {
        if (!CaptchaEnabled) {
            return;
        }
        if (!CaptchaSecretKey) {
            logger.error("Captcha is enabled but CAPTCHA_SECRET_KEY is not configured.");
            throw new BadDataException(GENERIC_ERROR_MESSAGE);
        }
        const token = (options.token || "").trim();
        if (!token) {
            throw new BadDataException("Captcha token is missing. Please complete the verification challenge.");
        }
        try {
            await this.verifyHCaptcha(token, options.remoteIp || undefined);
        }
        catch (err) {
            if (axios.isAxiosError(err)) {
                const axiosError = err;
                logger.error(`Captcha provider verification failure: ${axiosError.message}`);
            }
            else {
                logger.error(`Captcha provider verification failure: ${err.message}`);
            }
            throw new BadDataException(GENERIC_ERROR_MESSAGE);
        }
    }
    static async verifyHCaptcha(token, remoteIp) {
        var _a;
        const params = new URLSearchParams();
        params.append("secret", CaptchaSecretKey);
        params.append("response", token);
        if (remoteIp) {
            params.append("remoteip", remoteIp);
        }
        const response = await axios.post("https://hcaptcha.com/siteverify", params.toString(), {
            headers: {
                "content-type": "application/x-www-form-urlencoded",
            },
            timeout: REQUEST_TIMEOUT_MS,
        });
        if (!((_a = response.data) === null || _a === void 0 ? void 0 : _a.success)) {
            logger.warn(`hCaptcha verification failed: ${JSON.stringify(response.data || {})}`);
            throw new BadDataException(GENERIC_ERROR_MESSAGE);
        }
    }
}
export default CaptchaUtil;
//# sourceMappingURL=Captcha.js.map