import {handleError} from "../../notifications";
import {DEFAULT_CHATBOT_SETTINGS_KEY_PREFIX} from "../../../data/chatbot/settings";
import {GetSettings, UpdateSettings} from "../../../rest/settings";

/**
 * Connect storage to the default chatbot
 *
 * @param {number} vectorIndexId Storage ID
 * @param {function} addNotification Add notification
 * @param {object} notificationParams Notification params
 * @return {Promise<boolean>}
 * @constructor
 */
export const ConnectStorageToDefaultChatbot = async (vectorIndexId, addNotification, notificationParams = {}) => {
    if (!vectorIndexId) {
        // Invalid storage id
        return false;
    }
    try {
        // Settings keys
        const knowledgeBaseSettingKey = DEFAULT_CHATBOT_SETTINGS_KEY_PREFIX + 'knowledge_base';
        const kbVectorIndexIdsSettingKey = DEFAULT_CHATBOT_SETTINGS_KEY_PREFIX + 'kb_vector_index_ids';
        // Get already saved storages
        const res = await GetSettings(LimbChatbot.rest.url, LimbChatbot.rest.nonce, {
            key: [knowledgeBaseSettingKey, kbVectorIndexIdsSettingKey]
        });
        // Data
        const knowledgeBase = res?.find(item => item.key === knowledgeBaseSettingKey)?.value;
        const kbVectorIndexIds = res?.find(item => item.key === kbVectorIndexIdsSettingKey)?.value || [];
        // Data to save
        const dataToSave = [];
        // Enable knowledge base
        if (!knowledgeBase) {
            dataToSave.push({
                key: knowledgeBaseSettingKey,
                value: true,
            });
        }
        // Add storage
        if (!kbVectorIndexIds.includes(vectorIndexId)) {
            dataToSave.push({
                key: kbVectorIndexIdsSettingKey,
                value: [...kbVectorIndexIds, vectorIndexId],
            });
        }
        // Save settings
        if (dataToSave.length > 0) {
            await UpdateSettings(LimbChatbot.rest.url, LimbChatbot.rest.nonce, dataToSave);
        }

        return true;
    } catch (e) {
        handleError(e, addNotification, {
            title: __("Failed to connect storage to chatbot.", 'limb-chatbot'),
            description: e.message ? __(e.message, 'limb-chatbot') : __("Please check and try again.", 'limb-chatbot'),
            ...notificationParams
        });
    }
}

/**
 * Connect storage to chatbot
 *
 * @param {number} vectorIndexId Storage ID
 * @param {string|number} chatbotIdentifier Chatbot UUID or ID
 * @param {function} addNotification Add notification
 * @constructor
 */
export const ConnectStorageToChatbot = async (vectorIndexId, chatbotIdentifier, addNotification) => {
    if (
        !vectorIndexId // Invalid storage id
        || (!chatbotIdentifier && chatbotIdentifier !== null) // Invalid chatbot identifier, or not the default one
    ) {
        return false;
    }
    try {
        if (!chatbotIdentifier) {
            await ConnectStorageToDefaultChatbot(vectorIndexId, addNotification);
        } else {
            // TODO - add logic to connect storage to chatbot CPT
        }
        return true;
    } catch (e) {
        handleError(e, addNotification, {
            title: __("Failed to connect storage to chatbot.", 'limb-chatbot'),
            description: e.message ? __(e.message, 'limb-chatbot') : __("Please check and try again.", 'limb-chatbot'),
        });
    }
}