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

const SET_LOG_LEVEL_ERROR_MESSAGE = 'Failed to set application version log level. ' +
    'To get more details use the --verbose flag.';

export const setApplicationVersionLogLevel = async ({ console, profile, fetch, application, version, logLevel }) => {
    const serverUrl = profile?.server_url;
    if (!serverUrl) {
        console.debug('Can not set application version log level. Server URL is missing.');
        throw new Error(SET_LOG_LEVEL_ERROR_MESSAGE);
    }

    const token = profile?.token?.access_token;
    if (!token) {
        console.debug('Can not set application version log level. Access token is missing.');
        throw new Error(SET_LOG_LEVEL_ERROR_MESSAGE);
    }

    if (!application) {
        console.debug('Can not set application version log level. Application parameter is missing.');
        throw new Error(SET_LOG_LEVEL_ERROR_MESSAGE);
    }

    if (!version) {
        console.debug('Can not set application version log level. Version parameter is missing.');
        throw new Error(SET_LOG_LEVEL_ERROR_MESSAGE);
    }

    if (!logLevel) {
        console.debug('Can not set application version log level. Log level parameter is missing.');
        throw new Error(SET_LOG_LEVEL_ERROR_MESSAGE);
    }

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

    console.debug(`Setting log level for application version: ${String(apiUrl)}`);

    const res = await fetch(apiUrl, {
        method: 'PATCH',
        headers: {
            'Authorization': 'Bearer ' + token,
            'Content-Type': 'application/json'
        },
        body: logLevel
    });

    if (res.status !== 200 && res.status !== 204) {
        const detailedError = `Failed to set log level for application version: ${res.status} ${res.statusText} ` +
            await res.text();
        console.debug(detailedError);
        throw new Error(SET_LOG_LEVEL_ERROR_MESSAGE);
    }

    return {
        application,
        version,
        logLevel
    };
};
