import {defineStore} from 'pinia'
import {config} from '@/config'
import {useErrorStore} from "@/store/error.js";

export const useStageStore = defineStore('stage', {
    state() {
        return {
            stagedChanges: false
        }
    },
    getters: {
        hasStagedChanges(state) {
            return state.stagedChanges;
        },
    },
    actions: {
        async checkStagedChanges() {
            const url = `${config.backendUrl}/properties/staged_changes`;
            this.stagedChanges = await this.performRequest('GET', url, null);
        },
        async applyChanges() {
            const url = `${config.backendUrl}/properties/staged_changes`;
            await this.performRequest('PUT', url, null, false);
            this.stagedChanges = false;
        },
        async performRequest(method, url, body, expectResponse = true) {

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

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

            const request = {url: url, params: params};
            console.log("Request:", request);

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

                console.error(error);
                const errorStore = useErrorStore();
                void errorStore.addError(error, {store: this, 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
                    }

                    console.error(error);
                    const errorStore = useErrorStore();
                    void errorStore.addError(error, {store: this, 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
                    }

                    console.error(error);
                    const errorStore = useErrorStore();
                    void errorStore.addError(error, {store: this, 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
                        }
                        console.error(error);
                        const errorStore = useErrorStore();
                        void errorStore.addError(error, {store: this, 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
                    }

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


                }
            }

            console.log("Response:", data);
            return data;
        }
    }

});