interface RecaptchaResponse {
    success: boolean;
    challenge_ts?: string;
    hostname?: string;
    'error-codes'?: string[];
    error_message?: string; // Added to include a custom error message
}

async function verifyRecaptcha(secret: string, response: string, remote_ip?: string): Promise<RecaptchaResponse> {
    const url = 'https://www.google.com/recaptcha/api/siteverify';

    try {
        const params = new URLSearchParams({
            secret,
            response,
            ...(remote_ip ? { remoteip:remote_ip } : {}),
        });

        const result = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params.toString(),
        });

        // Check if the HTTP response is OK (status 200-299)
        if (!result.ok) {
            console.error(`HTTP error! status: ${result.status}`);
            return {
                success: false,
                error_message: `HTTP error! status: ${result.status}`,
            };
        }

        const data = await result.json() as RecaptchaResponse;

        // Check if the reCAPTCHA verification was unsuccessful
        if (!data.success) {
            const errorCodes = data['error-codes']?.join(', ') || 'Unknown error';
            return {
                ...data,
                error_message: `reCAPTCHA verification failed: ${errorCodes}`,
            };
        }

        // Success case
        return data;
    } catch (error) {
        console.error('Failed to verify reCAPTCHA:', error);
        return {
            success: false,
            error_message: 'An unexpected error occurred while verifying the reCAPTCHA token.',
        };
    }
}

// Export for both ESM and CommonJS environments
module.exports = { verifyRecaptcha };
export { verifyRecaptcha };
