import { create } from 'zustand'

const useAuthStore = create((set) => ({
  user: null,
  token: localStorage.getItem('manager_token') || null,
  savedUsername: localStorage.getItem('manager_username') || null,
  locked: false,

  login(user, token) {
    localStorage.setItem('manager_token', token)
    localStorage.setItem('manager_username', user.username)
    set({ user, token, savedUsername: user.username, locked: false })
  },

  logout() {
    localStorage.removeItem('manager_token')
    localStorage.removeItem('manager_username')
    localStorage.removeItem('manager_lock_timeout')
    set({ user: null, token: null, savedUsername: null, locked: false })
  },

  lock() {
    set({ locked: true })
  },

  unlock(user, token) {
    localStorage.setItem('manager_token', token)
    set({ user, token, locked: false })
  },
}))

export default useAuthStore
