import axios from "axios";
import { configStore, sessionTokensStore, userInfosStore } from "../store/store";
import { apiService } from "../utils/axios";
import { BASE_URL, CACHE_LIMITS, GET_USER_TAG_PAGE_LIMIT } from "../utils/constant";
import { getFileTypeFromMime } from "../utils/func";
import { blobCache } from "../utils/blob-cache";
import { getCachedMedia, persistMedia } from "../utils/cache";
export { createQuickMessageTemplate, createQuickMessageLibraryFiles, deleteQuickMessageTemplate, getQuickMessageLibraryFiles, getQuickMessageTemplates, updateQuickMessageLibraryFileName, updateQuickMessageTemplate, } from './quick-message';
import * as zdesk_1 from "./zdesk";
export { zdesk_1 as zdesk };
export const getChats = async (params) => {
    const { connections, lastAnswerByIds, statusIds, tagIds, userIds, zrmzCustomerIds, verifySlip, verifySlipValue, ...rest } = params;
    if (connections?.length === 0) {
        return {
            chats: []
        };
    }
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    let verifySlipParams = {};
    if (verifySlip && verifySlipValue) {
        if (verifySlip === 'total_completed_verify_slip') {
            verifySlipParams = { total_completed_verify_slip: verifySlipValue };
        }
        else {
            verifySlipParams = { total_completed_verify_slip_more_than: verifySlipValue };
        }
    }
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat`, {
        params: {
            ...rest,
            session_id: params.sessionId,
            connections: connections && connections.length > 0 ? JSON.stringify(connections.map(connection => ({
                id: connection.id,
                channel: connection.channel
            }))) : undefined,
            last_answer_by_id: lastAnswerByIds && lastAnswerByIds.length === configStore.get('memberList').length
                ? undefined
                : lastAnswerByIds,
            status_id: statusIds,
            tag_id: tagIds,
            user_id: userIds ? [...new Set(userIds)] : [],
            zrmz_customer_id: zrmzCustomerIds,
            ...verifySlipParams,
        },
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getChats');
};
export const searchChats = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat/search`, { params });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to searchChats');
};
export const getChatByUserId = async (params) => {
    const { userId } = params;
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat/user`, {
        params: {
            user_id: userId,
        }
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getChat');
};
export const getChat = async (params) => {
    const { sessionId } = params;
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat/${sessionId}`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getChat');
};
export const updateChat = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId, ...rest } = params;
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/chat/${sessionId}`, rest);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to updateUser');
};
export const translateChatMessage = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId, text, messageIds } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/chat/${sessionId}/translate`, {
        text,
        message_ids: messageIds,
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to updateUser');
};
export const getChatMessages = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId, startMessageId, ...rest } = params;
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat/${sessionId}/message`, {
        params: {
            start_message_id: startMessageId,
            ...rest,
        },
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getChatMessages');
};
export const searchChatMessages = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId, search } = params;
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat/${sessionId}/search-message`, { params: { search } });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to searchChatMessages');
};
export const getChatFiles = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId } = params;
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat/${sessionId}/files`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getChatFiles');
};
export const sendMessage = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId, messages } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/chat/${sessionId}/send-message`, {
        messages: (messages || []).map(({ mimeType, replyMessageId, buttons, menu_list, packageId, stickerId, fileId, ...rest }) => ({
            ...rest,
            package_id: packageId,
            sticker_id: stickerId,
            file_id: fileId,
            mime_type: mimeType,
            reply_message_id: replyMessageId,
            buttons: (buttons || undefined)?.map(({ action_type, text, action }) => ({ alt_text: text, action_type, text, action: action || undefined })),
            menu_list: (menu_list || undefined)?.map(({ file_url, file_id, title, description, buttons }) => ({ file_url, file_id, title, description, buttons: (buttons || []).map(({ action_type, text, action }) => ({ action_type, text, action: action || undefined })), })),
        })),
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to sendMessage');
};
export const readMessage = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/chat/${sessionId}/read`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to readMessage');
};
export const unReadMessage = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/chat/${sessionId}/mark-as-unread`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to unReadMessage');
};
export const getMessageMedia = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { channel, sessionId, messageId, file } = params;
    // Check in-memory cache first (fastest)
    const cached = blobCache.get(channel, sessionId, messageId);
    if (cached) {
        if (cached.hasError) {
            return null;
        }
        return cached;
    }
    // Check if there's already a pending request for this media
    const pending = blobCache.getPending(channel, sessionId, messageId);
    if (pending) {
        return pending;
    }
    try {
        const idbCached = await getCachedMedia(channel, sessionId, messageId);
        if (idbCached) {
            const blob = new Blob([idbCached.arrayBuffer], { type: idbCached.contentType });
            const blobUrl = URL.createObjectURL(blob);
            const blobType = getFileTypeFromMime(blob.type);
            blobCache.set(channel, sessionId, messageId, blobUrl, blobType);
            return { url: blobUrl, type: blobType };
        }
    }
    catch (error) {
        console.warn('IndexedDB read failed — fall through to network', error);
    }
    // Create the fetch promise
    const fetchPromise = (async () => {
        const baseUrl = BASE_URL();
        const isExternalUrl = file?.url && !file.url.includes(baseUrl);
        const url = file ? file.url : `${baseUrl}/api/${businessId}/${shopId}/${channel}/${sessionId}/${messageId}/content`;
        let attempts = 0;
        const maxRetries = isExternalUrl ? 1 : 3;
        while (attempts < maxRetries) {
            try {
                const response = await axios.get(url, { responseType: 'arraybuffer' });
                const arrayBuffer = response.data;
                const contentType = response.headers['content-type'];
                const blob = new Blob([arrayBuffer], { type: contentType });
                const blobUrl = URL.createObjectURL(blob);
                const blobType = getFileTypeFromMime(blob.type);
                blobCache.set(channel, sessionId, messageId, blobUrl, blobType);
                blobCache.cleanup(100);
                if (!isExternalUrl) {
                    persistMedia(channel, sessionId, messageId, arrayBuffer, contentType).catch((error) => {
                        console.warn('Failed to persist media', error);
                    });
                }
                return { url: blobUrl, type: blobType };
            }
            catch (error) {
                attempts++;
                if (isExternalUrl && file?.url) {
                    console.warn('CORS blocked for external URL, using direct URL instead:', file.url);
                    const fileType = file.mime_type ? getFileTypeFromMime(file.mime_type) : { type: 'unknown' };
                    blobCache.set(channel, sessionId, messageId, file.url, fileType);
                    return { url: file.url, type: fileType };
                }
                if (attempts >= maxRetries) {
                    const errorMessage = error instanceof Error ? error.message : 'Failed to fetch media';
                    console.error(`Failed to fetch media after ${maxRetries} attempts`, errorMessage);
                    blobCache.setError(channel, sessionId, messageId);
                    return null;
                }
                await new Promise(resolve => setTimeout(resolve, 500));
            }
        }
        return null;
    })();
    // Store the pending promise
    blobCache.setPending(channel, sessionId, messageId, fetchPromise);
    try {
        return await fetchPromise;
    }
    finally {
        // Clear pending after completion
        blobCache.clearPending(channel, sessionId, messageId);
    }
};
//Waiting for resolve expired attachments from facebook eg. attachments.find((item) => item.type === 'video'|'image').payload.url;
export const getMessageAttachment = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { channel, sessionId, messageId } = params;
    const baseUrl = BASE_URL();
    const url = `${baseUrl}/api/${businessId}/${shopId}/${channel}/${sessionId}/${messageId}/attachment`;
    let attempts = 0;
    const maxRetries = 3;
    while (attempts < maxRetries) {
        try {
            const response = await axios.get(url, {
                responseType: 'blob',
            });
            const blobUrl = URL.createObjectURL(response.data);
            return blobUrl;
        }
        catch (error) {
            attempts++;
            if (attempts >= maxRetries) {
                const errorMessage = error instanceof Error ? error.message : 'Failed to fetch attachment';
                console.error(`Failed to fetch attachment after ${maxRetries} attempts`, errorMessage);
                return null;
            }
            await new Promise(resolve => setTimeout(resolve, 500));
        }
    }
    return null;
};
export const getUser = async (params) => {
    const { type = 'user', channel, id, sessionId } = params;
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    let route = `user/${channel}/${id}`;
    if (type === 'group') {
        route = `${channel}/group/${id}`;
    }
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/${route}`, { params: { session_id: sessionId } });
    if (status === 200) {
        let addressFormat = null;
        if (data.address && Object.keys(data.address).length > 0) {
            addressFormat = {
                address: data.address ? data.address.address || '' : '',
                province: data.address ? data.address.province || '' : '',
                district: data.address ? data.address.district || '' : '',
                sub_district: data.address ? data.address.sub_district || data.address.subdistrict || '' : '',
                zip_code: data.address ? data.address.zip_code || '' : '',
            };
        }
        return {
            ...data, address: addressFormat
        };
    }
    throw new Error('Failed to getUser');
};
export const getActivityLogs = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { type = 'user', channel, id } = params;
    let route = `user/${channel}/${id}/activity-log`;
    if (type === 'group') {
        route = `${channel}/group/${id}/activity_logs`;
    }
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/${route}`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getActivityLogs');
};
export const updateUser = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { type = 'user', channel, id } = params;
    let _channel = channel;
    if (type === 'group') {
        _channel = 'line';
    }
    let route = `user/${_channel}/${id}`;
    if (type === 'group') {
        route = `${_channel}/group/${id}`;
    }
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/${route}`, {
        nickname: params.nickname,
        email: params.email,
        phone_number: params.phone_number,
        address: params.address,
        gender: params.gender,
        locale: params.locale,
        note: params.note,
        status_id: params.status_id,
        add_tag_ids: params.add_tag_ids,
        remove_tag_ids: params.remove_tag_ids,
        context: params.context,
        session: params.session,
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to updateUser');
};
export const mergeUser = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { matchUserId, matchDecision } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/user/merge`, {
        match_user_id: matchUserId,
        match_decision: matchDecision,
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to mergeUser');
};
export const unlinkUser = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { zignalUserId, channel, userId } = params;
    const { data, status } = await apiService().request({
        method: 'DELETE',
        url: `api/${businessId}/${shopId}/user/unlink`,
        data: {
            zignal_user_id: zignalUserId,
            channel: channel,
            user_id: userId,
        },
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to unlinkUser');
};
export const getUserStatuses = async () => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/user/status`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getUserStatuses');
};
export const createUserStatus = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/user/status`, params);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to createUserStatus');
};
export const getUserTags = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { search, limit = GET_USER_TAG_PAGE_LIMIT, offset = 0 } = params;
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/user/tag`, { params: { search, limit, offset } });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getUserTags');
};
export const createUserTag = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/user/tag`, params);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to createUserTag');
};
export const updateUserStatus = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { id, ...rest } = params;
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/user/status/${id}`, rest);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to updateUserStatus');
};
export const deleteUserStatus = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { id, force, checkOnly } = params;
    const { data, status } = await apiService().delete(`api/${businessId}/${shopId}/user/status/${id}`, {
        data: { force, check_only: checkOnly }
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to deleteUserStatus');
};
export const reorderUserStatus = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { id, sequence } = params;
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/user/status/${id}`, {
        sequence
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to reorderUserStatus');
};
export const resequenceUserStatus = async () => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/user/status/resequence`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to resequenceUserStatus');
};
export const updateUserTag = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { id, ...rest } = params;
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/user/tag/${id}`, rest);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to updateUserTag');
};
export const deleteUserTag = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { id, force, checkOnly } = params;
    const { data, status } = await apiService().delete(`api/${businessId}/${shopId}/user/tag/${id}`, {
        data: { force, check_only: checkOnly }
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to deleteUserTag');
};
export const reorderUserTag = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { id, sequence } = params;
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/user/tag/${id}`, {
        sequence
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to reorderUserTag');
};
export const resequenceUserTag = async () => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/user/tag/resequence`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to resequenceUserTag');
};
export const createUserContext = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/user/context`, params);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to createUserContext');
};
export const saveUserEvent = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/chat/${sessionId}/zwiz/save-user-event`, params);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to saveUserEvent');
};
export const getReplyTokenInfo = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId } = params;
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat/${sessionId}/reply-token-info`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getReplyTokenInfo');
};
export const syncMessage = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/chat/${sessionId}/sync-message`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to syncMessage');
};
export const syncTags = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { sessionId } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/chat/${sessionId}/sync-tag`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to syncTags');
};
export const syncUser = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { channel, id } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/user/${channel}/${id}/sync`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to syncUser');
};
// Custom Filter API Functions
export const getChatFilters = async () => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat/filters`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getChatFilters');
};
export const createChatFilter = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { connections, last_answer_by_ids, status_ids, tag_ids, ...rest } = params;
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/chat/filters`, {
        ...rest,
        connections,
        last_answer_by_ids,
        status_ids,
        tag_ids,
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to createChatFilter');
};
export const updateChatFilter = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { id, connections, last_answer_by_ids, status_ids, tag_ids, ...rest } = params;
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/chat/filters/${id}`, {
        ...rest,
        connections,
        last_answer_by_ids,
        status_ids,
        tag_ids,
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to updateChatFilter');
};
export const deleteChatFilter = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().delete(`api/${businessId}/${shopId}/chat/filters/${params.id}`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to deleteChatFilter');
};
export const getChatFilterConfig = async () => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/chat/filter-config`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getChatFilterConfig');
};
export const getShopUrl = async ({ connectionId, channel, userId, urlType }) => {
    const { data, status } = await apiService().post(`api/zwiz/${connectionId}/shop-url`, {
        channel,
        user_id: userId,
        url_type: urlType,
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getShopUrl');
};
export const initConnection = async (params) => {
    const { channel, connectionId, syncChatMessage = true, syncTag = true } = params;
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const url = `api/connection/${businessId}/${shopId}/${channel}/${connectionId}/init`;
    const { status, data } = await apiService().post(url, channel === 'facebook' ? {
        sync_chat_message: syncChatMessage,
        sync_tag: syncTag
    } : {});
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to initConnection');
};
export const getConnectionJobs = async () => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().get(`api/connection/${businessId}/${shopId}/job`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getConnectionJobs');
};
export const deleteConnectionJob = async (params) => {
    const { connectionId } = params;
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const url = `api/connection/${businessId}/${shopId}/job/${connectionId}`;
    const { status, data } = await apiService().delete(url);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to deleteConnectionJob');
};
export const getUserCart = async (params) => {
    const { connectionId, channel, userId } = params;
    const { data, status } = await apiService().get(`api/zwiz/${connectionId}/user/${channel}/${userId}/cart`);
    if (status === 200) {
        return data.carts;
    }
    throw new Error('Failed to getUserCart');
};
export const clearUserCart = async (params) => {
    const { connectionId, channel, userId } = params;
    const { data, status } = await apiService().delete(`api/zwiz/${connectionId}/user/${channel}/${userId}/cart`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to clearUserCart');
};
export const getZwizCheckBotPage = async (connectionId) => {
    const { data, status } = await apiService().get(`api/zwiz/${connectionId}/check-bot-page`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getZwizCheckBotPage');
};
export const getZervaProfile = async (connectionId) => {
    const { data, status } = await apiService().get(`api/zwiz/zerva/${connectionId}/profile`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getZervaProfile');
};
export const getZervaShopUrl = async (connectionId, params) => {
    const { data, status } = await apiService().post(`api/zwiz/zerva/${connectionId}/shop-url`, params);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getZervaShopUrl');
};
export const getZrmzShopUrl = async (connectionId, params) => {
    const { data, status } = await apiService().post(`api/zwiz/zrmz/${connectionId}/shop-url`, params);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getZrmzShopUrl');
};
export const getZrmzShopProfile = async (connectionId) => {
    const { data, status } = await apiService().get(`api/zwiz/zrmz/${connectionId}/profile`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getZrmzShopProfile');
};
export const getZrmzCustomerInfo = async (connectionId, customerId) => {
    const { data, status } = await apiService().get(`api/zwiz/zrmz/${connectionId}/customer`, {
        params: {
            customer_id: customerId,
        },
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getZrmzCustomerInfo');
};
export const getZrmzPointHistory = async (params) => {
    const { connectionId, customerId, limit, offset } = params;
    const { data, status } = await apiService().get(`/api/zwiz/zrmz/${connectionId}/point-history`, {
        params: {
            customer_id: customerId,
            limit,
            offset,
        },
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getZrmzPointHistory');
};
export const createZrmzCustomer = async (params) => {
    const { connectionId, ...rest } = params;
    const { data, status } = await apiService().post(`api/zwiz/zrmz/${connectionId}/customer`, rest);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to createZrmzCustomer');
};
export const getZwizUserProfile = async (connectionId, channel, userId) => {
    const { data, status } = await apiService().get(`api/zwiz/${connectionId}/get-user-only`, {
        params: {
            channel,
            user_id: userId,
        },
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getZwizUserProfile');
};
export const updateZrmzCustomer = async (params) => {
    const { connectionId, customer_id, ...rest } = params;
    const { data, status } = await apiService().patch(`api/zwiz/zrmz/${connectionId}/customer`, {
        customer_id,
        ...rest,
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to updateZrmzCustomer');
};
export const disconnectZrmzCustomer = async (params) => {
    const { connectionId, ...rest } = params;
    const { data, status } = await apiService().request({
        method: 'DELETE',
        url: `api/zwiz/zrmz/${connectionId}/disconnect-customer`,
        data: rest
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to disconnectZrmzCustomer');
};
export const getZrmzCondition = async (params) => {
    const { connectionId } = params;
    const { data, status } = await apiService().get(`api/zwiz/zrmz/${connectionId}/condition`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getZrmzCondition');
};
export const adjustZrmzCustomerPoint = async (params) => {
    const { connectionId, ...rest } = params;
    const { data, status } = await apiService().post(`api/zwiz/zrmz/${connectionId}/adjust-point`, rest);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to adjustZrmzCustomerPoint');
};
export const adjustZrmzCustomerPointByCondition = async (params) => {
    const { connectionId, ...rest } = params;
    const { data, status } = await apiService().post(`api/zwiz/zrmz/${connectionId}/adjust-point-by-condition`, rest);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to adjustZrmzCustomerPointByCondition');
};
export const getUserOrders = async (params) => {
    const { connectionId, channel, userId } = params;
    const { data, status } = await apiService().get(`api/zwiz/${connectionId}/user/${channel}/${userId}/order`);
    if (status === 200) {
        return data.orders;
    }
    throw new Error('Failed to getUserOrders');
};
export const updateUserOrder = async (params) => {
    const { connectionId, channel, userId, orderId, amount, status, trackingNo, sendTrackingStatus, reason, sendReason, shipping_address } = params;
    const data = {};
    if (amount !== undefined) {
        data.amount = amount;
    }
    if (status !== undefined) {
        data.status = status;
        // Add tracking number and send tracking status only if status is 'shipped'
        if (status === 'shipped') {
            if (trackingNo !== undefined && trackingNo.length > 0) {
                data.tracking_no = trackingNo;
            }
            if (sendTrackingStatus !== undefined) {
                data.send_tracking_status = sendTrackingStatus;
            }
        }
        // Add reason and send reason only if status is 'canceled'
        if (status === 'canceled') {
            if (reason !== undefined && reason.length > 0) {
                data.reason = reason;
            }
            if (sendReason !== undefined) {
                data.send_reason = sendReason;
            }
        }
    }
    if (shipping_address !== undefined) {
        data.shipping_address = shipping_address;
    }
    const { data: responseData, status: responseStatus } = await apiService().patch(`api/zwiz/${connectionId}/user/${channel}/${userId}/order/${orderId}`, data);
    if (responseStatus === 200) {
        return responseData;
    }
    throw new Error('Failed to updateUserOrder');
};
export const getUserToken = async (params) => {
    const { connectionId } = params;
    const userInfo = userInfosStore.get(connectionId);
    if (userInfo?.token?.access_token) {
        return userInfo.token;
    }
    const { data, status } = await apiService().post(`api/zwiz/${connectionId}/user/token`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getUserToken');
};
export const getPlatformConnections = async () => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().get(`api/zwiz/${businessId}/${shopId}/platform-connection`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getPlatformConnections');
};
export const getSessionToken = async (params) => {
    const { connectionId, botId, channel, type, userId, groupId } = params;
    const cacheKey = [connectionId, botId, channel, type, userId || '', groupId || ''].join('::');
    const cachedToken = sessionTokensStore.get(cacheKey);
    if (cachedToken?.token && cachedToken.cachedAt) {
        const isExpired = Date.now() - cachedToken.cachedAt >= CACHE_LIMITS.SESSION_TOKEN_TTL_MS;
        if (!isExpired) {
            return cachedToken.token;
        }
        sessionTokensStore.set(cacheKey, {});
    }
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    const { data, status } = await apiService().post(`api/zwiz/${businessId}/${shopId}/${connectionId}/${channel}/get-session-token`, {
        bot_id: botId,
        type,
        user_id: userId,
        group_id: groupId,
    });
    if (status === 200) {
        sessionTokensStore.set(cacheKey, { token: data, cachedAt: Date.now() });
        return data;
    }
    throw new Error('Failed to getSessionToken');
};
export const getGroupMembers = async (params) => {
    const { type = 'user', channel, id } = params;
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (type !== 'group')
        return;
    const route = `${channel}/group/${id}/member`;
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/${route}`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getUser');
};
