import { createElectronStorageAdapter } from './storageAdapter';
import { getLocalFileServerInfo } from './localFileServer';
let cachedBaseUrl;
const ensureLocalFileServerBaseUrl = async () => {
    if (!cachedBaseUrl) {
        const info = await getLocalFileServerInfo();
        cachedBaseUrl = info.baseUrl;
    }
    return cachedBaseUrl;
};
const uploadAttachment = async (payload) => {
    const baseUrl = await ensureLocalFileServerBaseUrl();
    const response = await fetch(`${baseUrl}/files`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
    });
    const result = await response.json().catch(() => ({ error: 'Invalid JSON response from local file server' }));
    if (!response.ok) {
        const reason = typeof result?.error === 'string' ? result.error : response.statusText;
        throw new Error(`Failed to upload file: ${reason}`);
    }
    if (!result?.sourceUrl || typeof result.sourceUrl !== 'string') {
        throw new Error('Local file server response missing sourceUrl');
    }
    return { sourceUrl: result.sourceUrl };
};
export const attachmentCallbackHandler = async (payload) => {
    return uploadAttachment(payload);
};
let storageAdapter = null;
const getStorageAdapter = () => {
    if (!storageAdapter) {
        storageAdapter = createElectronStorageAdapter();
    }
    return storageAdapter;
};
export const electronStorage = {
    createAdapter: createElectronStorageAdapter,
    get adapter() {
        return getStorageAdapter();
    },
    attachmentCallbackHandler
};
