import { error } from '../model/error.js';
import { getApiUrl } from '../model/url.js';

export const uploadGacdContent = async ({ console, profile, fetch, path, file }) => {
    const serverUrl = profile?.server_url;
    if (!serverUrl) {
        const err = new Error('Can not upload content using GACD API. Server URL is missing.');
        throw err;
    }

    const token = profile?.token?.access_token;
    if (!token) {
        const err = new Error('Can not upload content using GACD API. Access token is missing.');
        throw err;
    }

    if (typeof path === 'undefined') {
        const err = new Error('Can not upload content using GACD API. GACD API path parameter is missing.');
        throw err;
    }

    if (!file) {
        const err = new Error('Can not upload content using GACD API. File parameter is missing.');
        throw err;
    }

    const apiUrl = getApiUrl(serverUrl, `./${path}/files/upload`);

    console.debug(`Uploading content using GACD API: ${String(apiUrl)}`);
    const formData = new FormData();
    formData.append('file', file);
    const res = await fetch(apiUrl, {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + token,
        },
        body: formData
    });
    if (res.status !== 200) {
        throw error(
            `Failed to upload content using GACD API: ${res.status} ${res.statusText} ` +
            await res.text(),
            res.status
        );
    }
    return await res.json();
};
