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

export const getGacdDeploymentStatus = async ({ console, profile, fetch, path, deploymentId }) => {
    const serverUrl = profile?.server_url;
    if (!serverUrl) {
        const err = new Error('Can not get GACD deployment status. Server URL is missing.');
        throw err;
    }

    const token = profile?.token?.access_token;
    if (!token) {
        const err = new Error('Can not get GACD deployment status. Access token is missing.');
        throw err;
    }

    if (typeof path === 'undefined') {
        const err = new Error('Can not get GACD deployment status. GACD API path is missing.');
        throw err;
    }

    if (!deploymentId) {
        const err = new Error('Can not get GACD deployment status. Deployment ID is missing.');
        throw err;
    }

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

    console.debug(`Getting GACD deployment status from: ${String(apiUrl)}`);
    const res = await fetch(apiUrl, {
        method: 'GET',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    });
    if (res.status !== 200) {
        throw error(
            `Failed to get GACD deployment status due to server error: ${res.status} ${res.statusText} ` +
            await res.text(),
            res.status
        );
    }
    return await res.json();
};
