import { verifyRecaptcha } from "../../utils/utils";
export async function executeRecaptcha(configId, siteKey, controlType, dataKey, dataMode, onError) {
    var _a;
    try {
        await loadRecaptchaV3(siteKey);
        await new Promise((resolve, reject) => {
            if (window.grecaptcha && typeof window.grecaptcha.ready === "function") {
                window.grecaptcha.ready(() => resolve());
            }
            else {
                reject(new Error("grecaptcha not available or ready() not a function"));
            }
        });
        if (!window.grecaptcha || typeof window.grecaptcha.execute !== "function") {
            throw new Error("grecaptcha.execute is not available. Possibly due to invalid site key.");
        }
        const token = await window.grecaptcha.execute(siteKey, { action: "open_chat" });
        if (!token) {
            throw new Error("reCAPTCHA token is empty. Possibly invalid site key.");
        }
        const result = await verifyRecaptchaToken(token, configId, controlType, dataKey, dataMode);
        return result;
    }
    catch (err) {
        const detail = (_a = err === null || err === void 0 ? void 0 : err.detail) !== null && _a !== void 0 ? _a : {
            message: err instanceof Error ? err.message : "reCAPTCHA execution failed",
            error: err,
        };
        onError === null || onError === void 0 ? void 0 : onError(detail);
        console.error("executeRecaptcha error:", err);
        throw err;
    }
}
export async function verifyRecaptchaToken(captchaToken, configId, controlType, dataKey, dataMode) {
    try {
        const payload = {
            apiKey: dataKey,
            configId,
            configType: controlType,
            token: captchaToken,
        };
        const data = await verifyRecaptcha(payload, dataMode);
        if (data === null || data === void 0 ? void 0 : data.success) {
            // console.log("reCAPTCHA verified successfully by backend!")
            return data; // Return the data
        }
        else {
            const detail = {
                message: `${controlType} verification failed`,
                codes: data === null || data === void 0 ? void 0 : data["error-codes"],
                error: data,
            };
            console.warn(`${controlType} activity suspected. Verification failed.`, detail.codes);
            const error = new Error(`${controlType} verification failed: reCAPTCHA was unsuccessful`);
            error.detail = detail;
            throw error;
        }
    }
    catch (err) {
        console.error("Failed to contact backend for reCAPTCHA verification:", err);
        if (!(err === null || err === void 0 ? void 0 : err.detail)) {
            const error = err;
            error.detail = {
                message: "reCAPTCHA backend error",
                error: err,
            };
        }
        throw err;
    }
}
export function loadRecaptchaV3(siteKey) {
    return new Promise((resolve, reject) => {
        if (!document.querySelector("#recaptcha-script")) {
            const script = document.createElement("script");
            script.src = `https://www.google.com/recaptcha/api.js?render=${siteKey}`;
            script.id = "recaptcha-script";
            script.async = true;
            script.onload = () => {
                resolve();
            };
            script.onerror = err => {
                console.error("Failed to load reCAPTCHA script", err);
                reject(new Error("Failed to load reCAPTCHA script. Invalid siteKey or network error."));
            };
            document.head.appendChild(script);
        }
        else {
            resolve();
        }
    });
}
