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


export const useActiveUserStore = defineStore('activeUser', {
    state: () => {
        return {
            user: null,
        }
    },
    getters: {
        allowCalculation(state) {
            if (state.user === null)
                return false;
            return state.user.groups?.includes("super") || state.user.groups?.includes("calculation");
        },
        allowConfiguration(state) {
            if (state.user === null)
                return false;
            return state.user.groups?.includes("super") || state.user.groups?.includes("freight") || state.user.groups?.includes("packaging") || state.user.groups?.includes("service") || state.user.groups?.includes("material");
        },
        allowReporting(state) {
            if (state.user === null)
                return false;
            return state.user.groups?.includes("super") || state.user.groups?.includes("freight") || state.user.groups?.includes("packaging") || state.user.groups?.includes("material") || state.user.groups?.includes("basic") || state.user.groups?.includes("calculation");
        },
        isSuper(state) {
            if (state.user === null)
                return false;
            return state.user.groups?.includes("super");
        },
        isService(state) {
            if (state.user === null)
                return false;
            return state.user.groups?.includes("service");
        },
        isPackaging(state) {
            if (state.user === null)
                return false;
            return state.user.groups?.includes("packaging");
        },
        isFreight(state) {
            if (state.user === null)
                return false;
            return state.user.groups?.includes("freight");
        },
        isMaterial(state) {
            if (state.user === null)
                return false;
            return state.user.groups?.includes("material");
        },
        allowRates(state) {
            if (state.user === null)
                return false;
            return state.user.groups?.includes("super") || state.user.groups?.includes("freight");
        }

    },
    actions: {
        async loadIfRequired() {
            if (this.user === null)
                await this.load();
        },
        async load() {
            const resp = await performRequest(this, "GET", `${config.backendUrl}/active-user`, null, true);
            this.user = resp.data;
        }
    }
});