import { createStore } from 'vuex';

const store = createStore({
  state: {
    token: localStorage.getItem('token') || null,
    username: localStorage.getItem('username') || '',
    currentClub: localStorage.getItem('currentClub') || null,
    clubs: localStorage.getItem('clubs') || [],
  },
  mutations: {
    setToken(state, token) {
      state.token = token;
      localStorage.setItem('token', token);
      state.currentClub = null;
      localStorage.setItem('currentClub', null);
    },
    setUsername(state, username) {
      state.username = username;
      localStorage.setItem('username', username);
    },
    setClub(state, club) {
      state.currentClub = club;
      localStorage.setItem('currentClub', club);
    },
    setClubsMutation(state, clubs) {
      state.clubs = clubs;
      localStorage.setItem('clubs', clubs);
    },
    clearToken(state) {
      state.token = null;
      localStorage.removeItem('token');
      router.push("/");
    },
    clearUsername(state) {
      state.username = '';
      localStorage.removeItem('username');
    }
  },
  actions: {
    login({ commit }, { token, username }) {
      commit('setToken', token);
      commit('setUsername', username);
    },
    logout({ commit }) {
      commit('clearToken');
      commit('clearUsername');
      router.push("/");
    },
    setCurrentClub({ commit }, club) {
      console.log('action', club);
      commit('setClub', club);
    }, 
    setClubs({ commit }, clubs) {
      commit('setClubsMutation', clubs);
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    token: state => state.token,
    username: state => state.username,
    currentClub: state => state.currentClub,
    clubs: state => state.clubs,
  },
});

export default store;
