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

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

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

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

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