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

export const useMaterialStore = defineStore('material', {
    state() {
        return {
            materials: [],
            loading: false,
            empty: true,
            error: null,
            query: {},
            pagination: {}
        }
    },
    getters: {},
    actions: {
        async setQuery(query) {
            this.query = query;
            await this.updateMaterials();
        },
        async updateMaterials() {

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

            const params = new URLSearchParams();

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


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

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

            const response = await fetch(url).catch(e => {
                this.error = {code: '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 = {
                    code: '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});

                return;
            }

            this.loading = false;
            this.empty = data.length === 0;
            this.materials = data;

        }
    }
});
