import logger from "@/logger.js";
import {useErrorStore} from "@/store/error.js";

const performRequest = async (requestingStore, method, url, body, expectResponse = true) => {

    const params = {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        }
    };

    if (body) {
        params.body = JSON.stringify(body);
    }

    const request = {url: url, params: params};
    logger.info("Request:", request);

    const response = await fetch(url, params
    ).catch(e => {
        const error = {
            code: 'Network error.',
            message: "Please check your internet connection.",
            trace: null
        }

        logger.error(error);
        const errorStore = useErrorStore();
        void errorStore.addError(error, {store: requestingStore, request: request});

        throw e;
    });

    let data = null;
    if (expectResponse) {
        data = await response.json().catch(e => {
            const error = {
                code: 'Malformed response',
                message: "Malformed server response. Please contact support.",
                trace: null
            }

            logger.error(error);
            const errorStore = useErrorStore();
            void errorStore.addError(error, {store: requestingStore, request: request});
            throw e;
        });

        if (!response.ok) {
            const error = {
                code: data.error.code,
                title: data.error.title,
                message: data.error.message,
                trace: data.error.trace
            }

            logger.error(error);
            const errorStore = useErrorStore();
            void errorStore.addError(error, {store: requestingStore, request: request});
            throw new Error('Internal backend error');
        }
    } else {
        if (!response.ok) {

            const data = await response.json().catch(e => {
                const error = {
                    code: "Return code error " + response.status,
                    message: "Server returned wrong response code",
                    trace: null
                }
                logger.error(error);
                const errorStore = useErrorStore();
                void errorStore.addError(error, {store: requestingStore, request: request});
                throw new Error('Internal backend error');

            });

            const error = {
                code: data.error.code,
                title: data.error.title,
                message: data.error.message,
                trace: data.error.trace
            }

            logger.error(error);
            const errorStore = useErrorStore();
            void errorStore.addError(error, {store: requestingStore, request: request});
            throw new Error('Internal backend error');
        }
    }

    logger.info("Response:", data);
    return data;
}

export default performRequest;
