import {urlSearchParams} from "../../../helpers";
import {handleResponse} from "../../helpers/rest";

/**
 * Get chatbots
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {object} params Query params
 * @return {Promise<any>}
 */
export const GetChatbots = (restUrl, restNonce, params = {}) => {
    const query = urlSearchParams(params);
    // Custom headers
    const customHeaders = {};
    // Page context
    if (LimbChatbot?.pageContext) {
        customHeaders['X-LBAIC-Page-Context'] = JSON.stringify(LimbChatbot.pageContext);
    }

    return fetch(`${restUrl}chatbots${query}`, {
        method: 'GET',
        cache: 'no-store', // Prevent caching
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce,
            ...customHeaders
        }
    }).then(handleResponse);
}

/**
 * Get chatbot
 *
 * @param {string} restUrl Rest url
 * @param {string} restNonce Rest nonce
 * @param {string} key Chatbot unique key
 * @param {object} params Query params
 * @return {Promise<any>}
 */
export const GetChatbot = (restUrl, restNonce, key, params = {}) => {
    const query = urlSearchParams(params);

    return fetch(`${restUrl}chatbots/${key}${query}`, {
        method: 'GET',
        cache: 'no-store', // Prevent caching
        headers: {
            'Accept': 'application/json',
            'X-WP-Nonce': restNonce
        }
    }).then(handleResponse);
}

/**
 * Get chatbot by UUID
 *
 * @param {string} uuid Chatbot UUID
 * @return {Promise<object>}
 * @constructor
 */
export const GetChatbotByUuid = async (uuid) => {
    try {
        // Handle default chatbot case
        if (uuid === 'default') {
            const res = await GetChatbots(LimbChatbot.rest.url, LimbChatbot.rest.nonce, {
                include: ['default', 'utility'],
                per_page: 1,
            });
            if (res?._default) {
                return {
                    ...res._default,
                    uuid: 'default',
                    title: res._default.utility?.title || __('Default Chatbot', 'limb-chatbot')
                };
            }
        } else {
            const res = await GetChatbot(LimbChatbot.rest.url, LimbChatbot.rest.nonce, uuid, {
                include: ['utility'],
            });
            if (res?.uuid) {
                return res;
            }
        }
    } catch (e) {
        console.error(e);
    }

    return null;
}