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

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

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

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

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

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

    console.debug(`Deleting application version: ${String(apiUrl)}`);
    const res = await fetch(apiUrl, {
        method: 'DELETE',
        headers: {
            'Authorization': 'Bearer ' + token
        }
    });
    if (res.status !== 204) {
        throw error(`Failed to delete application version: ${res.status} ${res.statusText} ` +
          await res.text(), res.status);
    }
};
