import {defineStore} from "pinia";
import {getFiltersForMainPage} from "@/utils/ftch.js";
import {md5} from "js-md5";

export const useProductFiltersStore = defineStore('product_filters', {
    state: () => ({
        isLoading: false,
        draft: {},
        applied: {},
        default: {},
        fullPath: '',
    }),

    getters: {
        paramsHashForRouter: (state) => md5(JSON.stringify({ filters: state.applied })),

        isFiltersChanged: (state) =>
            md5(JSON.stringify({ filters: state.applied })) !== md5(JSON.stringify({ filters: state.default })),
    },

    actions: {
        async fetchFiltersForMainPage() {
            if (this.isLoading) return;

            try {
                this.isLoading = true;
                const response = await getFiltersForMainPage();
                this.default = response.data;
                return response.data;
            } catch (error) {
                console.log(error);
            } finally {
                this.isLoading = false;
            }
        },

        clear() {
            this.filters = {};
        }
    },
});
