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

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

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

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

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

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