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

export const useMatrixRateStore = defineStore('matrixRate', {
    state() {
        return {
            rates: [],
            loading: false,
            empty: true,
            error: null,
            query: {},
            pagination: {}
        }
    },
    getters: {
        isLoading(state) {
            return state.loading;
        },
        getRates(state) {
            return state.rates;
        },
        getPagination(state) {
            return state.pagination;
        }
    },
    actions: {
        async setQuery(query = {}) {
            this.query = query;
            await this.updateMatrixRates();
        },
        async updateMatrixRates() {
            this.loading = true;

            const params = new URLSearchParams();
            if (this.query?.searchTerm && this.query.searchTerm !== '')
                params.append('filter', this.query.searchTerm);
            if(this.query?.periodId)
                params.append('valid', this.query.periodId);

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

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

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

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

            this.rates = data;
            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;

        }
    }

});