import {defineStore} from 'pinia'
import {config} from '@/config'
import {useNotificationStore} from "@/store/notification.js";
import performRequest from "@/backend.js";
import logger from "@/logger.js";

export const useMaterialStore = defineStore('material', {
    state() {
        return {
            materials: [],
            loading: false,
            empty: true,
            error: null,
            query: {},
            pagination: {}
        }
    },
    getters: {},
    actions: {
        async setQueryForList(query) {
          this.query = query;
          this.query.excludeDeprecated = false;
          await this.updateMaterials();
        },
        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);

            if(this.query?.page)
                params.append('page', this.query.page);

            if(this.query?.pageSize)
                params.append('limit', this.query.pageSize);

            if(this.query?.excludeDeprecated !== null)
                params.append('excludeDeprecated', this.query.excludeDeprecated);


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

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


            const {data: data, headers: headers} = await performRequest(this, "GET", url, null, true);

            this.pagination = {
                page: parseInt(headers.get('X-Current-Page')),
                pageCount: parseInt(headers.get('X-Page-Count')),
                totalCount: parseInt(headers.get('X-Total-Count'))
            };

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

        }
    }
});
