import { configStore } from "../store/store";
import { apiService } from "../utils/axios";
import { uploadFileService } from "../utils/upload";
import { getFileTypeFromMime } from "../utils/func";
const normalizeQuickMessageTemplateString = (value) => {
    if (value === undefined || value === null) {
        return undefined;
    }
    const trimmed = value.trim();
    return trimmed.length > 0 ? trimmed : undefined;
};
const isHttpUrl = (value) => {
    if (value == null)
        return false;
    try {
        const url = new URL(value);
        return url.protocol === 'http:' || url.protocol === 'https:';
    }
    catch (e) {
        return false;
    }
};
const isDataUrl = (value) => value.startsWith('data:');
const dataUrlToFile = (dataUrl) => {
    const matches = dataUrl.match(/^data:(.*?);base64,(.*)$/);
    if (!matches) {
        return null;
    }
    const mime = matches[1] || 'application/octet-stream';
    const base64Data = matches[2];
    try {
        const binaryString = atob(base64Data);
        const len = binaryString.length;
        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i += 1) {
            bytes[i] = binaryString.charCodeAt(i);
        }
        const extension = mime.split('/')[1] || 'bin';
        const fileName = `quick-message-${Date.now()}.${extension}`;
        return new File([bytes], fileName, { type: mime });
    }
    catch (error) {
        console.error('[quick-message-template] Failed to convert data URL to file', error);
        return null;
    }
};
const resolveFile = async (fileUrl, fileId) => {
    if (!fileUrl) {
        return fileId;
    }
    const normalized = normalizeQuickMessageTemplateString(fileUrl);
    if (!normalized) {
        return null;
    }
    if (isHttpUrl(normalized)) {
        return normalized;
    }
    if (isDataUrl(normalized)) {
        const file = dataUrlToFile(normalized);
        if (!file) {
            return normalized;
        }
        try {
            const response = await uploadFileService({
                file,
                filename: file.name.replaceAll(' ', '-'),
                usageType: 'quick_message_template',
            });
            return response.id;
        }
        catch (error) {
            console.error('[quick-message-template] Failed to upload file for template', error);
            return null;
        }
    }
    return null;
};
const buildQuickMessageTemplateRequestBody = async (template) => {
    const title = template.title ? template.title.trim() : '';
    const contents = await Promise.all((template.contents || []).map(async (content) => {
        const text = normalizeQuickMessageTemplateString(content.text);
        const filePath = await resolveFile(content.file_url, content.file?.id);
        const isFileUrl = isHttpUrl(filePath);
        const buttons = (content.buttons || [])
            .map(button => {
            const buttonText = normalizeQuickMessageTemplateString(button.text);
            if (!buttonText) {
                return null;
            }
            const payload = {
                action_type: button.action_type,
                text: buttonText,
            };
            const action = normalizeQuickMessageTemplateString(button.action);
            if (action) {
                payload.action = action;
            }
            return payload;
        })
            .filter((button) => Boolean(button));
        const menuListRaw = await Promise.all((content.menu_list || []).map(async (menu) => {
            const filePath = await resolveFile(menu.file_url, menu.file?.id);
            const isFileUrl = isHttpUrl(filePath);
            const titleMenu = normalizeQuickMessageTemplateString(menu.title);
            const descriptionMenu = normalizeQuickMessageTemplateString(menu.description);
            const menuButtons = (menu.buttons || [])
                .map(button => {
                const buttonText = normalizeQuickMessageTemplateString(button.text);
                if (!buttonText) {
                    return null;
                }
                const payload = {
                    action_type: button.action_type,
                    text: buttonText,
                };
                const action = normalizeQuickMessageTemplateString(button.action);
                if (action) {
                    payload.action = action;
                }
                return payload;
            })
                .filter((button) => Boolean(button));
            if (!filePath && !titleMenu && !descriptionMenu && menuButtons.length === 0) {
                return null;
            }
            const payload = {};
            if (isFileUrl) {
                payload.file_url = filePath;
            }
            else {
                payload.file_id = filePath;
            }
            if (titleMenu) {
                payload.title = titleMenu;
            }
            if (descriptionMenu) {
                payload.description = descriptionMenu;
            }
            if (menuButtons.length > 0) {
                payload.buttons = menuButtons;
            }
            return payload;
        }));
        const menuList = menuListRaw.filter((menu) => Boolean(menu));
        if (!text && !filePath && buttons.length === 0 && menuList.length === 0) {
            return null;
        }
        const payload = {
            type: content.type,
        };
        if (text) {
            payload.text = text;
        }
        if (filePath != null) {
            if (isFileUrl) {
                payload.file_url = filePath;
            }
            else {
                payload.file_id = filePath;
                payload.type = 'file';
            }
        }
        if (buttons.length > 0) {
            payload.buttons = buttons;
        }
        if (menuList.length > 0) {
            payload.menu_list = menuList;
        }
        return payload;
    }));
    const filteredContents = contents.filter((content) => Boolean(content));
    return {
        title,
        contents: filteredContents,
    };
};
const normalizeLibraryFilesResponse = (data) => {
    if (Array.isArray(data)) {
        return data;
    }
    if (data && typeof data === 'object' && Array.isArray(data.files)) {
        return data.files;
    }
    return [];
};
export const getQuickMessageTemplates = async (params = {}) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (!businessId || !shopId) {
        throw new Error('[quick-message] Missing businessId or shopId');
    }
    const { page = 1, limit = 20, search, is_zwiz, connection_id } = params;
    const requestParams = {
        page,
        limit,
        search: search ? search.trim() : undefined,
        is_zwiz,
        connection_id,
    };
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/quick-message-template`, {
        params: requestParams,
    });
    if (status === 200) {
        for (const t of data.templates) {
            for (const c of t.contents) {
                if (c.file?.mime_type) {
                    const type = getFileTypeFromMime(c.file?.mime_type);
                    if (type.type == 'image') {
                        c.type = 'image';
                    }
                }
            }
        }
        return data;
    }
    throw new Error('Failed to getQuickMessageTemplates');
};
export const createQuickMessageTemplate = async (template) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (!businessId || !shopId) {
        throw new Error('[quick-message] Missing businessId or shopId');
    }
    const payload = await buildQuickMessageTemplateRequestBody(template);
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/quick-message-template`, payload);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to createQuickMessageTemplate');
};
export const updateQuickMessageTemplate = async (template) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (!businessId || !shopId) {
        throw new Error('[quick-message] Missing businessId or shopId');
    }
    if (!template.id) {
        throw new Error('[quick-message] Missing template id');
    }
    const payload = await buildQuickMessageTemplateRequestBody(template);
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/quick-message-template/${template.id}`, payload);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to updateQuickMessageTemplate');
};
export const deleteQuickMessageTemplate = async (templateId) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (!businessId || !shopId) {
        throw new Error('[quick-message] Missing businessId or shopId');
    }
    if (!templateId) {
        throw new Error('[quick-message] Missing template id');
    }
    const { data, status } = await apiService().delete(`api/${businessId}/${shopId}/quick-message-template/${templateId}`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to deleteQuickMessageTemplate');
};
export const createQuickMessageLibraryFiles = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (!businessId || !shopId) {
        throw new Error('[quick-message] Missing businessId or shopId');
    }
    const files = params.files || [];
    if (files.length === 0) {
        return [];
    }
    const requestPayload = {
        files: files.map(file => ({
            file_type: file.file_type,
            name: file.name.trim(),
            size: file.size,
            file_id: file.file_id?.trim(),
        })),
    };
    const { data, status } = await apiService().post(`api/${businessId}/${shopId}/quick-message-library-file`, requestPayload);
    if (status === 200) {
        return normalizeLibraryFilesResponse(data);
    }
    throw new Error('Failed to createQuickMessageLibraryFiles');
};
export const deleteQuickMessageLibraryFile = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (!businessId || !shopId) {
        throw new Error('[quick-message] Missing businessId or shopId');
    }
    const normalizedIds = Array.from(new Set((params.ids || []).map(id => (typeof id === 'string' ? id.trim() : '')).filter(id => id.length > 0)));
    if (normalizedIds.length === 0) {
        throw new Error('[quick-message] Missing file ids to delete');
    }
    const { data, status } = await apiService().delete(`api/${businessId}/${shopId}/quick-message-library-file`, {
        data: {
            file_ids: normalizedIds,
        },
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to deleteQuickMessageLibraryFile');
};
export const updateQuickMessageLibraryFileName = async (params) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (!businessId || !shopId) {
        throw new Error('[quick-message] Missing businessId or shopId');
    }
    const trimmedId = params.id.trim();
    const trimmedName = params.name.trim();
    if (!trimmedId) {
        throw new Error('[quick-message] Missing file id to update');
    }
    if (!trimmedName) {
        throw new Error('[quick-message] Missing file name to update');
    }
    const { data, status } = await apiService().patch(`api/${businessId}/${shopId}/quick-message-library-file/${trimmedId}`, {
        name: trimmedName,
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to updateQuickMessageLibraryFileName');
};
export const getQuickMessageLibraryFiles = async (params = {}) => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (!businessId || !shopId) {
        throw new Error('[quick-message] Missing businessId or shopId');
    }
    const { page = 1, limit = 20, search, fileType } = params;
    const requestParams = {
        page,
        limit,
        search: search ? search.trim() : undefined,
        file_type: fileType,
    };
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/quick-message-library-file`, {
        params: requestParams,
    });
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getQuickMessageLibraryFiles');
};
export const getQuickMessageLibraryFilesStorageUsage = async () => {
    const businessId = configStore.get('businessId');
    const shopId = configStore.get('shopId');
    if (!businessId || !shopId) {
        throw new Error('[quick-message] Missing businessId or shopId');
    }
    const { data, status } = await apiService().get(`api/${businessId}/${shopId}/quick-message-library-file/storage-usage`);
    if (status === 200) {
        return data;
    }
    throw new Error('Failed to getQuickMessageLibraryFilesStorageUsage');
};
