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

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

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

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

    if (!property.name) {
        const err = new Error('Can not update application property. Property name is missing.');
        throw err;
    }

    if (!property.hasOwnProperty('value')) {
        const err = new Error('Can not update application property. Property value is missing.');
        throw err;
    }

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

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