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

export const useErrorLogStore = defineStore('errorLog', {
    state() {
        return {
            errors: [],
            loading: false,
            query: {},
            pagination: {}
        }
    },
    getters: {
        isLoading(state) {
            return state.loading;
        },
        getErrors(state) {
            return state.errors;
        },
        getPagination(state) {
            return state.pagination;
        }

    },
    actions: {
        async setQuery(query = {}) {
            this.query = query;
            await this.updateErrors();
        },
        async updateErrors() {
            this.loading = true;

            this.errors = [];

            const params = new URLSearchParams();
            if (this.query?.searchTerm && 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);

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

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

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

        }
    }

});