import { createStore } from 'vuex'
export default createStore({
  state: {
    name:"No name set",
    user:{
      name:"Guest",
      id:0,
      entities:[]
    },
    isLoggedIn:false,
    alerts:[],
    axiosInstance:null,
    entity:0
  },
  getters: {
    getName(state){
      return state.name;
    },
    getUser(state){
      return state.user;
    },
    isLoggedIn(state){
      return state.isLoggedIn;
    },    isAdmin(state){
      const acl = state.user?.acl;
      if (!Array.isArray(acl)) return false;
      return acl.some((a) => {
        if (a.name !== 'User') return false;
        const gm = a.GroupModules || {};
        return !!(gm.create && gm.read && gm.update && gm.delete);
      });
    },
    isUserGroupMember(state){
      const groups = state.user?.groups;
      if (!Array.isArray(groups)) return false;
      return groups.some((name) => String(name || '').trim().toLowerCase() === 'user');
    },    getAlerts(state){
      return state.alerts;
    },
    getAxios(state){
      return state.axiosInstance;
    },
    getEntity(state){
      return state.entity
    }
  },
  mutations: {
    setName(state,val){
      state.name=val;
    },
    setUser(state,val){
      state.user=val;
    },
    setIsLoggedIn(state,val){
      state.isLoggedIn=val;
    },
    addAlert(state,val){
      state.alerts.push(val);
    },
    pushNotif(state,val){
      state.alerts.push(val);
    },
    dismissAlert(state,val){
      state.alerts=state.alerts.filter((alert,ind)=>ind!=val);
    },
    setAxiosInstance(state,val){
      state.axiosInstance=val;
    },
    setEntity(state,val){
      state.entity=val;
    }
  },
  actions: {
    logout(context,p){
      context.commit('setIsLoggedIn',false);
      context.commit('setUser',{name:"Guest",id:0});
      context.commit('addAlert',{type:"info",message:p.message,title:p.title});
    },
    loggedOut(context){
      context.commit('setIsLoggedIn',false);
      context.commit('setUser',{name:"Guest",id:0});
      context.commit('setEntity',0);
      context.commit('addAlert',{type:"danger",message:"You are not Logged In!",title:"Session Log Out!"});
    },

  },
  modules: {
  }
})
