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

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

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

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

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

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

    console.debug(`Getting GACD deployment logs 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 logs due to server error: ${res.status} ${res.statusText} ` +
            await res.text(),
            res.status
        );
    }
    return await res.json();
};
