import {defineStore} from "pinia";
import ftch from "../utils/ftch.js";

export const useCategoriesStore = defineStore('categories', {
    state: () => ({
        topCategories: [],
        categories: [],
        isLoading: false,
        isCategoriesLoaded: false,
    }),

    actions: {
        async fetchCategories() {
            if (this.isCategoriesLoaded === false && this.categories.length === 0) {
                try {
                    this.isLoading = true;
                    const {data} = await ftch('categoriesList');
                    this.categories = data;
                    this.isCategoriesLoaded = true;
                } catch (error) {
                    console.error(error);
                } finally {
                    this.isLoading = false;
                }
            }
        },

        async findCategoryById(id, list = []) {
            if (! id) return null;

            if (list && list.length === 0) {
                await this.fetchCategories();
                list = this.categories;
            }

            for (const cat of list) {
                if (parseInt(cat.id) === parseInt(id)) return cat;
                if (cat.children?.length) {
                    const found = await this.findCategoryById(id, cat.children);
                    if (found) return found;
                }
            }

            return null;
        }
    },
});
