import { ref } from "vue";
import { defineStore } from "pinia";
import { chatbotService } from "src/modules/chatbot/services/chatbot.service";
import type { Message } from "src/modules/chatbot/models/dialogue-message.model";
import { type ChatbotPageContext, PageContexts } from "src/modules/chatbot/models/page-context.model";
import type { RouteNames } from "src/router/router-constants";

export const useChatbotStore = defineStore("chatbot", () => {
    const messages = ref<Message[]>([]);
    const has_shown_instructions = ref(false);
    const is_showing_chatbot = ref(false);
    const current_page_context = ref<ChatbotPageContext | undefined>(undefined);

    const sendChatMessage = async (user_message: string) => {
        const last_chatbot_message = messages.value.at(messages.value.length - 1)!;

        try {
            const chatbot_response = await chatbotService.sendChatMessage(user_message, current_page_context.value);
            if (chatbot_response) {
                last_chatbot_message.text = chatbot_response.text;
                last_chatbot_message.isThinking = false;
            } else {
                last_chatbot_message.text = 'chatbot.error.NO_REPLY_RECEIVED';
                last_chatbot_message.isThinking = false;
            }
        }
        catch (error) {
            last_chatbot_message.text = 'chatbot.error.SEND_MESSAGE_FAILED';
            last_chatbot_message.isThinking = false;
            console.error('error sending message: ', error);
        }
    };

    const updatePageContext = (page_name: RouteNames) => {
        current_page_context.value = PageContexts[page_name] ?? undefined;
    
    };

    const showInstructionsOnce = () => {
        if (!has_shown_instructions.value) {
            messages.value.push({
                text: "chatbot.chat_initial_message",
                sent: false,
                isThinking: false,
            });
            has_shown_instructions.value = true;
        }
    };

    return {
        messages,
        has_shown_instructions,
        is_showing_chatbot,
        sendChatMessage,
        updatePageContext,
        showInstructionsOnce,
    };
});