import axios from 'axios';

const state = {
    isAuthenticated: false,
    token: null,
};

const mutations = {
    setUser(state, {token}) {
        state.isAuthenticated = true;
        state.token = token;
    },
    clearUser(state) {
        state.isAuthenticated = false;
        state.token = null;
    },
};

const actions = {
    async login({commit}, credentials) {
        const response = await axios.post('/api/login', credentials);
        if (response.status === 200) {
            commit('setUser', {token: response.data.token});
        }
        return response;
    },
    logout({commit}) {
        commit('clearUser');
    },
};

const getters = {
    isAuthenticated: (state) => state.isAuthenticated,
    user: (state) => state.user,
    token: (state) => state.token,
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters,
};
