import { create, insertMultiple } from '@orama/orama';
import { DOCS_PRESET_SCHEMA } from './constants.js';
export const restFetcher = async (url, options) => {
    const response = await fetch(url, options);
    if (response.status === 0) {
        throw new Error(`Request failed (network error): ${await response.text()}`);
    }
    else if (response.status >= 400) {
        const error = new Error(`Request failed (HTTP error ${response.status})}`);
        error.response = response;
        throw error;
    }
    return await response.json();
};
export async function loggedOperation(preMessage, fn, postMessage) {
    if (preMessage != null) {
        console.debug(preMessage);
    }
    try {
        const response = await fn();
        if (postMessage != null) {
            console.debug(postMessage);
        }
        return response;
    }
    catch (error) {
        throw new Error(`Error: ${error.message}`);
    }
}
export async function fetchEndpointConfig(baseUrl, APIKey, indexId) {
    const result = await loggedOperation('Orama: Fetch index endpoint config', async () => await restFetcher(`${baseUrl}/indexes/get-index?id=${indexId}`, {
        headers: {
            Authorization: `Bearer ${APIKey}`
        }
    }), 'Orama: Fetch index endpoint config (success)');
    return { endpoint: result === null || result === void 0 ? void 0 : result.api_endpoint, api_key: result === null || result === void 0 ? void 0 : result.api_key, collection_id: '' };
}
export async function createOramaInstance(oramaDocs) {
    console.debug('Orama: Creating instance.');
    const db = create({
        schema: { ...DOCS_PRESET_SCHEMA, version: 'enum' }
    });
    await insertMultiple(db, oramaDocs);
    console.debug('Orama: Instance created.');
    return db;
}
