import axios from 'axios';
import { ref } from 'vue';
import { defineStore } from 'pinia';
import { toLowerCamel } from 'src/filters';
import { useRole } from 'src/composables/useRole';
import routes from 'src/router/modules';

export const useNavigationStore = defineStore('navigationStore', () => {
    const modules = [
        'shelving',
        'order',
        'customer',
        'entry',
        'travel',
        'invoiceOut',
        'invoiceIn',
        'supplier',
        'claim',
        'route',
        'ticket',
        'worker',
        'wagon',
    ];
    const pinnedModules = ref([]);
    const role = useRole();

    function getModules() {
        const modulesRoutes = ref([]);
        for (const module of modules) {
            const moduleDef = routes.find((route) => toLowerCamel(route.name) === module);
            if (!moduleDef) continue;

            const item = addMenuItem(module, moduleDef, modulesRoutes.value);
            if (!item) continue;

            item.module = module;
            item.isPinned = false;

            if (pinnedModules.value.includes(module)) {
                item.isPinned = true;
            }
        }

        return modulesRoutes;
    }

    function getPinnedModules() {
        const modules = getModules();

        return modules && modules.value.filter((item) => item.isPinned);
    }

    function addMenuItem(module, route, parent) {
        const { meta } = route;
        let { menuChildren = null } = meta;
        if (menuChildren)
            menuChildren = menuChildren.map(({ name, title, icon }) => ({
                name,
                icon,
                title: `${module}.pageTitles.${title}`,
            }));

        if (meta && meta.roles && role.hasAny(meta.roles) === false) return;

        const item = {
            name: route.name,
            children: menuChildren,
        };
        if (meta) {
            item.title = `${module}.pageTitles.${meta.title}`;
            item.icon = meta.icon;
        }

        parent.push(item);

        return item;
    }

    async function fetchPinned() {
        if (pinnedModules.value.length) return;

        const response = await axios.get('StarredModules/getStarredModules');
        pinnedModules.value = response.data.map((row) => row.moduleFk);
    }

    function togglePinned(module) {
        if (pinnedModules.value.includes(module)) {
            const index = pinnedModules.value.indexOf(module);
            pinnedModules.value.splice(index, 1);

            return;
        }

        pinnedModules.value.push(module);
    }

    return {
        modules,
        pinnedModules,
        getModules,
        getPinnedModules,
        fetchPinned,
        togglePinned,
        addMenuItem,
    };
});
