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

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

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

    if (!application) {
        const err = new Error('Can not get application. Application parameter is missing.');
        throw err;
    }

    const apiUrl = getApiUrl(serverUrl, `./v1/applications/${application}`);

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