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

export const usePremiseStore = defineStore('premise', {
    state: () => ({
        premises: [],
        loading: false,
        empty: true,
        error: null,
        query: {},
        pagination: {}
    }),
    getters: {
        getById: (state) => { return (id) => state.premises.find(p => p.id === id)},
        showData: (state) => !state.loading && state.empty === false,
        showLoading: (state) => state.loading,
        showEmpty: (state) => !state.loading && state.empty === true,
        selectedIds: state => state.premises?.filter(p => p.checked).map(p => p.id) ?? [],
    },
    actions: {
        setQuery(query) {
            this.query = query;
            this.updatePremises();
        },
        async updatePremises() {

            this.premises = [];
            this.loading = true;
            this.empty = true;

            const params = new URLSearchParams();

            if (this.query.searchTerm)
                params.append('filter', this.query.searchTerm);

            if (this.query.archived)
                params.append('archived', this.query.archived);

            if (this.query.done)
                params.append('done', this.query.done);

            if (this.query.deleted)
                params.append('deleted', this.query.deleted);

            const url = `${config.backendUrl}/calculation/view/${params.size === 0 ? '' : '?'}${params.toString()}`;

            const request = { url: url, params: {method: 'GET'}};

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

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

                throw e;
            });

            const data = await response.json().catch(e => {
                this.error = { title: 'Malformed response', message: "Malformed server response. Please contact support.", trace: null }
                this.loading = false;

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

                throw e;
            });

            if (!response.ok) {
                this.error = { code: data.error.code, title: data.error.title, message: data.error.message, trace: data.error.trace }
                this.loading = false;

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

                console.log(data);
                return;
            }

            this.loading = false;
            this.empty = data.length === 0;
            data.forEach(p => p.checked = false);
            this.premises = data;

        }
    }
})