import { create } from 'zustand'

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

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

  // Restores user after a page refresh without touching the lock state.
  rehydrate(user, token) {
    set({ user, token, savedUsername: user.username })
  },

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

  lock() {
    sessionStorage.setItem('manager_locked', 'true')
    set({ locked: true })
  },

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

  updateUser(updatedUser) {
    localStorage.setItem('manager_username', updatedUser.username)
    set({ user: updatedUser })
  },
}))

export default useAuthStore
