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

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

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

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

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

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

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