import {defineStore} from "pinia";
import ftch from "@/utils/ftch.js";
import {YA_METRIKA_GOAL} from "@/constants/yaMetrikaGoals.js";
import {useYaMetrikaStore} from "@/stores/yaMetrikaStore.js";

export const useSearchStore = defineStore('search', {
    state: () => ({
        search: '',
        page: 1,
        products: {
            data: [],
            meta: {},
        },

        isLoading: false,
        isSearchPerformed: false,
    }),

    actions: {
        reset() {
            this.search = '';
            this.isSearchPerformed = false;
            this.isLoading = false;
            this.page = 1;
            this.products = {
                data: [],
                meta: {},
            };
        },

        async performSearch() {
            if (!this.search) {
                return this.reset();
            }

            useYaMetrikaStore().reachGoal(YA_METRIKA_GOAL.PERFORM_SEARCH, {
                keyword: this.search,
            });

            try {
                this.isLoading = true;
                this.products = await ftch('products', {
                    page: this.page,
                    perPage: 10,
                    search: this.search,
                });
            } catch (error) {
                console.error(error);
            } finally {
                this.isLoading = false;
                this.isSearchPerformed = true;
            }
        },
    },

});
