// src/store.js
import {
    createStore
} from 'vuex'

export default createStore({
    state: {
        user: null,
        authToken: null,
        refreshToken: null,
    },
    mutations: {
        SET_USER(state, user) {
            user.role_id = parseInt(user.role_id, 10);
            state.user = user;
            localStorage.setItem('user', JSON.stringify(user)); // Simpan user ke localStorage
        },
        SET_AUTH_TOKEN(state, token) {
            state.authToken = token;
            localStorage.setItem('authToken', token); // Simpan token ke localStorage
        },
        SET_REFRESH_TOKEN(state, token) {
            state.refreshToken = token;
            localStorage.setItem('refreshToken', token); // Simpan refresh token ke localStorage
        },
        CLEAR_AUTH_DATA(state) {
            state.user = null;
            state.authToken = null;
            state.refreshToken = null;
            localStorage.removeItem('user'); // Hapus data dari localStorage
            localStorage.removeItem('authToken');
            localStorage.removeItem('refreshToken');
            sessionStorage.removeItem('user'); // Hapus data dari sessionStorage jika ada
            sessionStorage.removeItem('authToken');
            sessionStorage.removeItem('refreshToken');
        }
    },
    actions: {
        setUser({
            commit
        }, user) {
            commit('SET_USER', user)
        },
        setAuthToken({
            commit
        }, token) {
            commit('SET_AUTH_TOKEN', token)
        },
        setRefreshToken({
            commit
        }, token) {
            commit('SET_REFRESH_TOKEN', token)
        },
        logout({
            commit
        }) {
            commit('CLEAR_AUTH_DATA')
        },
        checkAuth({
            commit
        }) {
            const user = JSON.parse(localStorage.getItem('user')) || JSON.parse(sessionStorage.getItem('user'))
            const authToken = localStorage.getItem('authToken') || sessionStorage.getItem('authToken')
            const refreshToken = localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken')
            if (user && authToken) {
                user.role_id = parseInt(user.role_id, 10)
                commit('SET_USER', user)
                commit('SET_AUTH_TOKEN', authToken)
                commit('SET_REFRESH_TOKEN', refreshToken)
            } else {
                commit('CLEAR_AUTH_DATA')
            }
        }
    },
    getters: {
        isAuthenticated(state) {
            return !!state.authToken
        },
        user(state) {
            return state.user
        },
        authToken(state) {
            return state.authToken
        },
        refreshToken(state) {
            return state.refreshToken
        }
    }
})
