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

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

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

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

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

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

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