// apis.ts
const MFS_API_BASE = 'https://mfs-api.midastix.com';

export const toAbsoluteUrl = (path?: string) => {
    if (!path) return '';
    if (path.startsWith('http://') || path.startsWith('https://')) return path;
    return `${MFS_API_BASE}${path}`;
};

/**
 * uploadFileXHR(file, onProgress, title?)
 * returns { success, data?, error? }
 */
export const uploadFileXHR = (
    file: File,
    onProgress: (pct: number) => void,
    title?: string
): Promise<{ success: boolean; data?: any; error?: string }> =>
    new Promise((resolve) => {
        try {
            const xhr = new XMLHttpRequest();
            const url = `${MFS_API_BASE}/image-upload/single`;
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Accept', 'application/json');

            xhr.upload.onprogress = (ev) => {
                if (!ev.lengthComputable) return;
                const pct = Math.round((ev.loaded / ev.total) * 100);
                onProgress(pct);
            };

            xhr.onload = () => {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const json = JSON.parse(xhr.responseText);
                        resolve({ success: true, data: json });
                    } catch (e) {
                        resolve({ success: true, data: xhr.responseText });
                    }
                } else {
                    const txt = xhr.responseText || `HTTP ${xhr.status}`;
                    resolve({ success: false, error: txt });
                }
            };

            xhr.onerror = () => resolve({ success: false, error: 'Network error' });

            const fd = new FormData();
            fd.append('file', file, file.name);
            if (title) fd.append('title', title);
            xhr.send(fd);
        } catch (err: any) {
            resolve({ success: false, error: err?.message ?? String(err) });
        }
    });

/* tolerant fetchImages mapping */
export const fetchImagesApi = async (title = '') => {
    const url =
        title && title.trim() !== '' ? `${MFS_API_BASE}/image-upload?title=${encodeURIComponent(title)}` : `${MFS_API_BASE}/image-upload`;
    const res = await fetch(url, { headers: { accept: 'application/json' } });
    if (!res.ok) {
        const txt = await res.text();
        throw new Error(txt || `HTTP ${res.status}`);
    }
    const body = await res.json();
    let imagesArray: any[] = [];
    if (Array.isArray(body)) imagesArray = body;
    else if (Array.isArray(body.images)) imagesArray = body.images;
    else if (body.data && Array.isArray(body.data.images)) imagesArray = body.data.images;
    else {
        const firstArray = Object.values(body).find((v) => Array.isArray(v));
        if (Array.isArray(firstArray)) imagesArray = firstArray as any[];
    }
    return imagesArray.map((it: any) => ({
        id: it.id ?? it._id ?? `${it.filename ?? Math.random()}`,
        url: toAbsoluteUrl(it.path ?? it.url),
        title: it.title ?? it.filename ?? '',
        date: it.created_at ?? it.createdAt ?? it.date ?? '',
        filename: it.filename,
        path: it.path,
        created_at: it.created_at ?? it.createdAt,
    }));
};

/* Delete photo (by id) */
export const deletePhotoApi = async (id: number | string) => {
    const url = `${MFS_API_BASE}/image-upload/${id}`;
    const res = await fetch(url, { method: 'DELETE', headers: { accept: 'application/json' } });
    const text = await res.text();
    if (!res.ok) throw new Error(text || `HTTP ${res.status}`);
    return text || 'deleted';
};

/* Delete folder by title (assumed endpoint) */
export const deleteFolderApi = async (title: string) => {
    const url = `${MFS_API_BASE}/image-upload/folder?title=${encodeURIComponent(title)}`;
    const res = await fetch(url, { method: 'DELETE', headers: { accept: 'application/json' } });
    const text = await res.text();
    if (!res.ok) throw new Error(text || `HTTP ${res.status}`);
    return text || 'folder deleted';
};
