/*
 * 管理员后台 API 封装：统一处理 chat_api 请求。
 * 作者: @ccfork
 */
export const apiUrl = 'chat_api.php';
const adminAuth = window.ADMIN_CONFIG?.auth || '';

export async function apiGet(action, params = {}) {
    const query = new URLSearchParams({ action, ...params });
    const res = await fetch(`${apiUrl}?${query.toString()}`, { cache: 'no-store' });
    return await res.json();
}

export async function apiPost(payload) {
    const res = await fetch(apiUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...payload, admin_auth: adminAuth })
    });
    return await res.json();
}

export function apiUploadImage({ sessionId, sender, file, reply, onProgress }) {
    const form = new FormData();
    form.append('action', 'send_image');
    form.append('session_id', sessionId);
    form.append('sender', sender);
    form.append('admin_auth', adminAuth);
    if (reply) form.append('reply', JSON.stringify(reply));
    form.append('image', file);
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', apiUrl);
        xhr.upload.onprogress = (event) => {
            if (event.lengthComputable && typeof onProgress === 'function') {
                onProgress(Math.round((event.loaded / event.total) * 100));
            }
        };
        xhr.onload = () => {
            try {
                resolve(JSON.parse(xhr.responseText || '{}'));
            } catch (error) {
                reject(error);
            }
        };
        xhr.onerror = () => reject(new Error('图片上传失败'));
        xhr.send(form);
    });
}
