import { openDB } from "idb";
import { getChatMessages, readMessage, translateChatMessage, unReadMessage } from "../api";
import { chatsStore, configStore, messagesStore, selectedChatStore, translateStore } from "./store";
import { MESSAGE_PAGE_LIMIT } from "../utils/constant";
import { getCachedMessages, persistMessages, updateMessageSyncState } from "../utils/cache";
import dayjs from "dayjs";
import { handleError } from "./dialog";
import { isValidTelNumber } from "../utils/func";
import { getButtonContentSchema, getMenuListContentSchema } from "../validations/schema";
import { useTranslation } from "../utils/utils";
let dbPromise;
export function initDB() {
    dbPromise = openDB('TranslationsDB', 1, {
        upgrade(db) {
            if (!db.objectStoreNames.contains('translations')) {
                db.createObjectStore('translations');
            }
        },
    });
}
function makeKey({ chat_id, message_id }) {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    return `${businessId}-${shopId}-${chat_id}-${message_id}`;
}
export async function getTranslation({ chat_id, message_ids }) {
    const db = await dbPromise;
    const keys = message_ids.map(message_id => makeKey({ chat_id, message_id }));
    const results = await Promise.all(keys.map(key => db.get('translations', key)));
    return results.filter((item) => !!item);
}
export async function storeTranslation(data) {
    const db = await dbPromise;
    const { chat_id, message_id } = data;
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const key = makeKey({ chat_id, message_id });
    const existing = await db.get('translations', key);
    await db.put('translations', {
        ...data,
        business_id: businessId,
        shop_id: shopId,
        created_at: Date.now(),
        is_translate_from_input: data.is_translate_from_input ?? existing?.is_translate_from_input,
    }, key);
}
export async function getTranslationsByChat({ business_id, shop_id, chat_id }) {
    const db = await dbPromise;
    const tx = db.transaction('translations', 'readonly');
    const store = tx.objectStore('translations');
    const all = [];
    let cursor = await store.openCursor();
    while (cursor) {
        if (cursor.value.business_id === business_id && cursor.value.shop_id === shop_id && cursor.value.chat_id === chat_id) {
            all.push(cursor.value);
        }
        cursor = await cursor.continue();
    }
    return all;
}
async function fetchAndStoreTranslation({ chat_id, message_ids }) {
    try {
        const translatedResponse = await translateChatMessage({
            sessionId: chat_id,
            messageIds: message_ids,
        });
        for (const message of translatedResponse.messages || []) {
            await storeTranslation({
                chat_id,
                message_id: message.id,
                translated_text: message.text,
            });
        }
        return translatedResponse;
    }
    catch (error) {
        handleError(error, 'Failed to Translate Chat Message');
    }
}
export async function getOrFetchTranslation({ chat_id, message_ids, referenceMessages, skipFetch = false, }) {
    if (message_ids.length === 0)
        return { messages: [] };
    const cachedTranslations = await getTranslation({ chat_id, message_ids });
    const messages = referenceMessages || messagesStore.get('messages');
    const validCached = [];
    const idsToFetch = [];
    const cachedMap = new Map(cachedTranslations.map(item => [item.message_id, item]));
    for (const id of message_ids) {
        const cached = cachedMap.get(id);
        if (cached) {
            const originalMsg = messages.find(m => m.id === id);
            if (originalMsg && originalMsg.text === cached.translated_text) {
                idsToFetch.push(id);
            }
            else {
                validCached.push({
                    id: cached.message_id,
                    text: cached.translated_text,
                    is_translate_from_input: cached.is_translate_from_input,
                });
            }
        }
        else {
            idsToFetch.push(id);
        }
    }
    let fetchedMessages = [];
    if (idsToFetch.length > 0 && !skipFetch) {
        const response = await fetchAndStoreTranslation({ chat_id, message_ids: idsToFetch });
        if (response && response.messages) {
            fetchedMessages = response.messages;
        }
    }
    return { messages: [...validCached, ...fetchedMessages] };
}
async function fetchJumpMessages(sessionId, startMessageId) {
    let allMessages = [];
    let currentNextKey;
    let currentPrevKey;
    const { messages, reads, next: nextKey, prev: prevKey, } = await getChatMessages({
        sessionId,
        limit: MESSAGE_PAGE_LIMIT,
        startMessageId,
    });
    if (!messages.length) {
        return { messages: [], reads, nextKey: undefined, prevKey: undefined };
    }
    allMessages = messages;
    currentNextKey = nextKey;
    currentPrevKey = prevKey;
    let safety = 0;
    while (allMessages.length < MESSAGE_PAGE_LIMIT && safety < 5) {
        if (currentPrevKey) {
            // Fetch newer messages
            const nextMessages = await getChatMessages({
                sessionId,
                limit: MESSAGE_PAGE_LIMIT,
                prev: currentPrevKey,
            });
            if (nextMessages.messages.length) {
                allMessages = allMessages.concat(nextMessages.messages);
                currentPrevKey = nextMessages.prev;
            }
            else {
                currentPrevKey = undefined;
            }
        }
        else if (currentNextKey) {
            // Fetch older messages
            const prevMessages = await getChatMessages({
                sessionId,
                limit: MESSAGE_PAGE_LIMIT,
                next: currentNextKey,
            });
            if (prevMessages.messages.length) {
                allMessages = allMessages.concat(prevMessages.messages);
                currentNextKey = prevMessages.next;
            }
            else {
                currentNextKey = undefined;
            }
        }
        else {
            break;
        }
        safety++;
    }
    return { messages: allMessages, reads, nextKey: currentNextKey, prevKey: currentPrevKey };
}
async function fetchOlderMessages(sessionId, next) {
    const { messages, reads, next: nextKey, prev: prevKey, } = await getChatMessages({
        sessionId,
        limit: MESSAGE_PAGE_LIMIT,
        next,
    });
    return { messages, reads, nextKey, prevKey };
}
async function fetchNewerMessages(sessionId, prev) {
    const { messages, reads, next: nextKey, prev: prevKey, } = await getChatMessages({
        sessionId,
        limit: MESSAGE_PAGE_LIMIT,
        prev,
    });
    return { messages, reads, nextKey, prevKey };
}
async function fetchInitMessages(sessionId) {
    const { messages, reads, next: nextKey, prev: prevKey, } = await getChatMessages({
        sessionId,
        limit: MESSAGE_PAGE_LIMIT,
    });
    return { messages, reads, nextKey, prevKey };
}
export async function handleGetChatMessages({ startMessageId, next, prev, isNewer = false, sessionId: callerSessionId, }) {
    const loadedKeys = messagesStore.get('loadedKeys');
    if ((next && loadedKeys.has(next)) || (prev && loadedKeys.has(prev)))
        return;
    const selectedChat = selectedChatStore.get('selectedChat');
    if (!selectedChat)
        return;
    // Use the caller-provided sessionId if available, otherwise fall back to current selectedChat
    const sessionId = callerSessionId || selectedChat.id;
    // Helper to check if the user has switched to a different chat since this call started
    const isStale = () => {
        const currentChat = selectedChatStore.get('selectedChat');
        return !currentChat || currentChat.id !== sessionId;
    };
    const isInitialLoad = !startMessageId && !next && !prev;
    if (isInitialLoad) {
        const cachedMessages = await getCachedMessages(sessionId);
        if (isStale())
            return; // Chat switched during cache fetch
        if (cachedMessages.length > 0 && messagesStore.get('messages').length === 0) {
            serviceUpdateMessageItems({ updateMessages: cachedMessages, clearMessages: true });
        }
    }
    let result = null;
    // 1. Fetch messages using helper functions
    if (startMessageId) {
        result = await fetchJumpMessages(sessionId, startMessageId);
    }
    else if (next) {
        result = await fetchOlderMessages(sessionId, next);
    }
    else if (prev) {
        result = await fetchNewerMessages(sessionId, prev);
    }
    else {
        result = await fetchInitMessages(sessionId);
    }
    // Bail out if the user switched chats while we were fetching
    if (isStale())
        return;
    if (!result || !result.messages.length)
        return;
    let { messages: allMessages } = result;
    const { reads, nextKey: currentNextKey, prevKey: currentPrevKey } = result;
    // 2. Prepare Translation (if needed)
    const translationSettings = configStore.get('translationSettings');
    const isAutoTranslate = translationSettings.is_auto &&
        selectedChat.language !== translationSettings.target_language &&
        !translationSettings.exclude_languages.includes(selectedChat.language);
    const translatedResponse = await getOrFetchTranslation({
        chat_id: sessionId,
        message_ids: allMessages.filter(item => item.text).map(item => item.id),
        referenceMessages: allMessages,
        skipFetch: !isAutoTranslate,
    });
    // Bail out if the user switched chats during translation
    if (isStale())
        return;
    const translatedMap = new Map((translatedResponse.messages || []).map(m => [
        m.id,
        {
            text: m.text,
            is_translate_from_input: m.is_translate_from_input
        }
    ]));
    if (translatedMap.size > 0) {
        const translatedMessages = translateStore.get('translatedMessages');
        const translatedMessagesMeta = translateStore.get('translatedMessagesMeta');
        const newTranslatedMessages = { ...translatedMessages };
        const newTranslatedMessagesMeta = { ...translatedMessagesMeta };
        let hasChanged = false;
        translatedMap.forEach((val, key) => {
            if (val.text && newTranslatedMessages[key] !== val.text) {
                newTranslatedMessages[key] = val.text;
                hasChanged = true;
            }
            if (val.is_translate_from_input && !newTranslatedMessagesMeta[key]?.isTranslateFromInput) {
                newTranslatedMessagesMeta[key] = { isTranslateFromInput: true };
                hasChanged = true;
            }
        });
        if (hasChanged) {
            translateStore.set('translatedMessages', newTranslatedMessages);
            translateStore.set('translatedMessagesMeta', newTranslatedMessagesMeta);
        }
    }
    allMessages = allMessages.map(item => {
        const translatedObject = translatedMap.get(item.id);
        if (translatedObject) {
            return {
                ...item,
                translatedText: translatedObject.text,
                isTranslateFromInput: translatedObject.is_translate_from_input ?? item.isTranslateFromInput,
            };
        }
        return item;
    });
    // 3. Update Store
    const isJumpMessage = Boolean(startMessageId);
    serviceUpdateMessageItems({ updateMessages: allMessages, clearMessages: isJumpMessage });
    messagesStore.set('reads', reads);
    // 4. Update pagination keys
    if (isJumpMessage) {
        messagesStore.set('older', { next: currentNextKey, prev: undefined });
        messagesStore.set('newer', { next: undefined, prev: currentPrevKey });
        messagesStore.set('jumpMessageId', startMessageId);
    }
    else {
        const keys = { next: currentNextKey, prev: currentPrevKey };
        messagesStore.set(isNewer ? 'newer' : 'older', keys);
    }
    // 5. Track loaded keys
    if (next || prev) {
        messagesStore.set('loadedKeys', new Set([...loadedKeys, next, prev]));
    }
    setTimeout(() => {
        handleMapReadMessage();
    }, 1000);
    // 6. Persist messages to IndexedDB cache (non-blocking)
    // Only persist non-sending messages (actual server messages)
    const persistableMessages = allMessages.filter(m => !m.isSending && m.id);
    const saveSync = () => {
        return updateMessageSyncState(sessionId);
    };
    if (persistableMessages.length > 0) {
        persistMessages(sessionId, persistableMessages).then(saveSync);
    }
    else {
        saveSync();
    }
}
export function serviceUpdateMessageItems({ updateMessages, clearSending = false, clearMessages = false, }) {
    const selectedChat = selectedChatStore.get('selectedChat');
    const channel = selectedChat ? selectedChat.channel : undefined;
    const mappedUpdateMessages = updateMessages
        .map(item => mapTemplateContent(item, channel))
        .filter((item) => Boolean(item));
    if (!mappedUpdateMessages.length)
        return;
    const messages = clearMessages ? [] : messagesStore.get('messages');
    const newMessages = mappedUpdateMessages;
    const oldMessages = messages;
    const messageMap = new Map();
    for (const m of oldMessages) {
        messageMap.set(m.id, m);
    }
    // Incoming messages (from API/Socket) always overwrite old/cached messages
    for (const m of newMessages) {
        messageMap.set(m.id, m);
    }
    let finalMessages = Array.from(messageMap.values());
    if (clearSending) {
        finalMessages = finalMessages.filter(item => !item.isSending);
    }
    // Sort final messages chronologically ascending
    finalMessages.sort((a, b) => dayjs(a.message_at).valueOf() - dayjs(b.message_at).valueOf());
    messagesStore.set('messages', finalMessages);
}
export function handleMapReadMessage() {
    setTimeout(() => {
        const reads = messagesStore.get('reads');
        const messages = messagesStore.get('messages');
        if (messages.length === 0 || reads.length === 0) {
            messagesStore.set('readsMap', {});
            return;
        }
        const readsMap = {};
        const sortedMessages = [...messages]
            .map(msg => ({
            id: msg.id,
            timestamp: dayjs(msg.message_at).valueOf()
        }))
            .sort((a, b) => a.timestamp - b.timestamp);
        const validReads = reads
            .filter(read => read.read_at)
            .map(read => ({
            reader: {
                ...read,
                picture_url: configStore.get('memberList').find((member) => member.id === read.id)?.member_account.picture_url || read.picture_url || ''
            },
            timestamp: dayjs(read.read_at).valueOf()
        }))
            .sort((a, b) => a.timestamp - b.timestamp);
        if (validReads.length === 0) {
            messagesStore.set('readsMap', {});
            return;
        }
        const assignedReadIndices = new Set();
        for (let i = sortedMessages.length - 1; i >= 0; i--) {
            const message = sortedMessages[i];
            const applicableReads = [];
            for (let j = 0; j < validReads.length; j++) {
                if (assignedReadIndices.has(j))
                    continue;
                if (validReads[j].timestamp > message.timestamp) {
                    applicableReads.push(validReads[j].reader);
                    assignedReadIndices.add(j);
                }
            }
            if (applicableReads.length > 0) {
                readsMap[message.id] = applicableReads;
            }
            if (assignedReadIndices.size === validReads.length) {
                break;
            }
        }
        messagesStore.set('readsMap', readsMap);
    }, 300);
}
export async function serviceReadMessage(sessionId) {
    const { last_read_at } = await readMessage({ sessionId });
    if (last_read_at) {
        serviceUpdateChatItem({
            chatId: sessionId,
            updateValue: {
                mark_as_unread: false,
                // unread_count: 0,
                is_unread: false,
                updated_at: last_read_at,
            },
        });
        return true;
    }
    return false;
}
export async function serviceUnReadMessage(sessionId) {
    const { code } = await unReadMessage({ sessionId });
    if (code === 'chat-marked-as-unread') {
        serviceUpdateChatItem({
            chatId: sessionId,
            updateValue: {
                mark_as_unread: true,
            },
        });
        return true;
    }
    return false;
}
export function serviceUpdateChatItem({ chatId, updateValue }) {
    const chats = chatsStore.get('chats');
    const idx = chats.findIndex(chat => chat.id === chatId);
    if (idx !== -1) {
        const updatedChats = [
            ...chats.slice(0, idx),
            {
                ...chats[idx],
                ...updateValue,
            },
            ...chats.slice(idx + 1),
        ];
        chatsStore.set('chats', updatedChats);
    }
}
export function scrollBottomMessage(chatId) {
    setTimeout(() => {
        const messageContainer = document.getElementById(`message-box-${chatId}`);
        if (messageContainer) {
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
    }, 100);
}
export function setHighlight(ranges) {
    if ('highlights' in CSS) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const highlightObj = new window.Highlight(...ranges);
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        CSS.highlights.set('search-result-highlight', highlightObj);
    }
}
export function clearHighlight() {
    if ('highlights' in CSS) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        CSS.highlights.delete('search-result-highlight');
    }
}
export function scrollToMessage({ messageId, force = false, focus = true, highlight = false, search }) {
    const messageElement = document.getElementById(`message-${messageId}`);
    if (messageElement) {
        messageElement.scrollIntoView({ behavior: force ? 'instant' : 'smooth' });
    }
    const messageContentElement = document.getElementById(`message-content-${messageId}`);
    if (messageContentElement) {
        if (focus) {
            messageContentElement.focus();
        }
        if (highlight && 'highlights' in CSS) {
            clearHighlight();
            if (search) {
                const ranges = [];
                const treeWalker = document.createTreeWalker(messageContentElement, NodeFilter.SHOW_TEXT);
                let currentNode = treeWalker.nextNode();
                while (currentNode) {
                    const textValue = currentNode.nodeValue;
                    if (textValue) {
                        let startIndex = 0;
                        const searchLower = search.toLowerCase();
                        const textLower = textValue.toLowerCase();
                        while ((startIndex = textLower.indexOf(searchLower, startIndex)) !== -1) {
                            const range = new Range();
                            range.setStart(currentNode, startIndex);
                            range.setEnd(currentNode, startIndex + search.length);
                            ranges.push(range);
                            startIndex += search.length;
                        }
                    }
                    currentNode = treeWalker.nextNode();
                }
                if (ranges.length > 0) {
                    setHighlight(ranges);
                }
            }
            else {
                const range = new Range();
                range.selectNodeContents(messageContentElement);
                setHighlight([range]);
            }
        }
        else if (highlight) {
            // Fallback for browsers that don't support CSS Custom Highlight API
            messageContentElement.classList.add('highlight');
            setTimeout(() => {
                messageContentElement.classList.remove('highlight');
            }, 2000);
        }
    }
    return Boolean(messageElement);
}
function generateTemplateId(prefix) {
    if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
        return `${prefix}-${crypto.randomUUID()}`;
    }
    return `${prefix}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`;
}
function createTemplateButton({ actionType, text, action, sequence, }) {
    const button = {
        id: generateTemplateId('btn'),
        action_type: actionType,
    };
    const trimmedText = text ? text.trim() : undefined;
    button.text = trimmedText || '';
    const trimmedAction = action ? action.trim() : undefined;
    if (trimmedAction) {
        button.action = trimmedAction;
    }
    if (typeof sequence === 'number') {
        button.sequence = sequence;
    }
    return button;
}
function createMenuListItem({ fileUrl, title, description, buttons, sequence, }) {
    const menuItem = {
        id: generateTemplateId('menu'),
        buttons,
    };
    const trimmedFileUrl = fileUrl ? fileUrl.trim() : undefined;
    if (trimmedFileUrl) {
        menuItem.file_url = trimmedFileUrl;
    }
    const trimmedTitle = title ? title.trim() : undefined;
    menuItem.title = trimmedTitle || '';
    const trimmedDescription = description ? description.trim() : undefined;
    menuItem.description = trimmedDescription || '';
    if (typeof sequence === 'number') {
        menuItem.sequence = sequence;
    }
    return menuItem;
}
function mapLineActionType(type) {
    if (!type)
        return 'text';
    switch (type.toLowerCase()) {
        case 'url':
        case 'uri':
        case 'web_url':
            return 'url';
        case 'tel':
        case 'phone_number':
            return 'tel';
        default:
            return 'text';
    }
}
function mapLineTemplateActions(actions) {
    if (!actions || actions.length === 0) {
        return [];
    }
    return actions
        .map((action, index) => {
        const type = action?.type;
        const label = action?.label;
        const text = action?.text || action?.title || action?.label;
        const uri = action?.uri || action?.url || action?.payload || action?.data;
        let actionType = mapLineActionType(type || label);
        if (actionType === 'text' && uri && isValidTelNumber(uri)) {
            actionType = 'tel';
        }
        return createTemplateButton({
            actionType,
            text: typeof text === 'string' ? text : '',
            action: typeof uri === 'string' ? uri : undefined,
            sequence: index + 1,
        });
    })
        .filter(button => Boolean(button.text || button.action));
}
function mapMetaActionType(type) {
    switch (type) {
        case 'web_url':
            return 'url';
        case 'phone_number':
            return 'tel';
        default:
            return 'text';
    }
}
function mapMetaPayloadButtons(buttons) {
    if (!buttons || buttons.length === 0) {
        return [];
    }
    return buttons
        .map((button, index) => {
        const payload = button ? button.payload || button.url : undefined;
        const type = button ? button.type : undefined;
        // Auto-detect if payload is a phone number
        let actionType = mapMetaActionType(type);
        if (actionType === 'text' && payload && isValidTelNumber(payload)) {
            actionType = 'tel';
        }
        return createTemplateButton({
            actionType,
            text: button ? button.title : '',
            action: payload,
            sequence: index + 1,
        });
    })
        .filter(button => Boolean(button.text || button.action));
}
function processButtonContent({ message, channel, }) {
    if (!channel) {
        return { buttons: [] };
    }
    switch (channel) {
        case 'line': {
            const template = message.template;
            if (template && template.type === 'buttons') {
                return {
                    buttons: mapLineTemplateActions(template.actions),
                    text: template.text || message.text,
                };
            }
            break;
        }
        case 'facebook':
        case 'instagram': {
            const attachments = message.attachments || [];
            const buttons = [];
            let templateText;
            for (const attachment of attachments) {
                if (attachment.type !== 'template')
                    continue;
                const payload = attachment.payload;
                if (!payload || payload.template_type !== 'button')
                    continue;
                buttons.push(...mapMetaPayloadButtons(payload.buttons));
                if (!templateText && (payload.text || attachment.title)) {
                    templateText = payload.text || attachment.title;
                }
            }
            return { buttons, text: templateText };
        }
        default:
            break;
    }
    return { buttons: [] };
}
function processMenuListContent({ message, channel, }) {
    if (!channel) {
        return [];
    }
    switch (channel) {
        case 'line': {
            const template = message.template;
            if (!template) {
                return [];
            }
            if (template.type === 'carousel' || template.type === 'image_carousel') {
                const columns = template.columns || [];
                return columns
                    .map((column, index) => {
                    const buttons = mapLineTemplateActions(column ? column.actions : []);
                    const menuItem = createMenuListItem({
                        fileUrl: column ? column.thumbnailImageUrl : undefined,
                        title: column ? column.title : undefined,
                        description: column ? column.text : undefined,
                        buttons,
                        sequence: index + 1,
                    });
                    if (menuItem.buttons.length === 0 && !menuItem.file_url && !menuItem.title && !menuItem.description) {
                        return null;
                    }
                    return menuItem;
                })
                    .filter((menuItem) => menuItem !== null);
            }
            break;
        }
        case 'facebook':
        case 'instagram': {
            const attachments = message.attachments || [];
            const menuList = [];
            let sequence = 0;
            for (const attachment of attachments) {
                if (attachment.type !== 'template')
                    continue;
                const payload = attachment.payload;
                if (!payload || (payload.template_type !== 'generic' && !payload.generic))
                    continue;
                const elements = payload.elements || (payload.generic ? payload.generic.elements : []) || [];
                for (const element of elements) {
                    sequence += 1;
                    const buttons = mapMetaPayloadButtons(element ? element.buttons : []);
                    const menuItem = createMenuListItem({
                        fileUrl: element ? element.image_url : undefined,
                        title: element ? element.title : undefined,
                        description: element ? element.subtitle : undefined,
                        buttons,
                        sequence,
                    });
                    if (menuItem.buttons.length === 0 && !menuItem.file_url && !menuItem.title && !menuItem.description) {
                        continue;
                    }
                    menuList.push(menuItem);
                }
            }
            return menuList;
        }
        default:
            break;
    }
    return [];
}
function mapTemplateContent(message, channel) {
    const hasTemplateData = Boolean(message.template) || Boolean((message.attachments || []).some(attachment => attachment.type === 'template'));
    const selectedChat = selectedChatStore.get('selectedChat');
    const selectedChannel = channel || (selectedChat ? selectedChat.channel : null);
    if (!selectedChannel) {
        return hasTemplateData ? null : message;
    }
    if (!hasTemplateData) {
        return message;
    }
    const { buttons, text: buttonText } = processButtonContent({ message, channel: selectedChannel });
    const menuList = processMenuListContent({ message, channel: selectedChannel });
    const hasButtons = buttons.length > 0;
    const hasMenuList = menuList.length > 0;
    if (!hasButtons && !hasMenuList) {
        return null;
    }
    const nextMessage = {
        ...message,
        text: message.text || buttonText || '',
        type: hasMenuList ? 'menu_list' : hasButtons ? 'button' : message.type,
    };
    nextMessage.buttons = hasButtons ? buttons : undefined;
    nextMessage.menu_list = hasMenuList ? menuList : undefined;
    return nextMessage;
}
export function getMessagePicture(sender, item) {
    if (!item)
        return '';
    if (item.type === 'user') {
        return sender.picture_url || (item.user ? item.user.picture_url : '');
    }
    if (item.type === 'group') {
        return sender.picture_url || (item.group ? item.group.picture_url : '');
    }
    return '';
}
export function validateMessageTemplate(content) {
    const t = useTranslation();
    let validator;
    if (content.type === 'button') {
        // validate button content.text too
        validator = getButtonContentSchema(t).safeParse({
            type: content.type,
            text: content.text,
            buttons: content.buttons,
        });
    }
    else if (content.type === 'menu_list') {
        validator = getMenuListContentSchema(t).safeParse({
            type: content.type,
            menu_list: content.menu_list,
        });
    }
    if (validator && !validator.success) {
        const firstError = validator.error.issues[0];
        const errorMessage = firstError ? firstError.message : 'Validation failed';
        handleError(new Error(errorMessage), 'Template validation failed');
        return false;
    }
    return true;
}
