import { defineStore } from 'pinia'
import { ref } from 'vue'

const REDIRECT_KEY = 'logout_redirect_path'

export const useAuthStore = defineStore('auth', () => {
  const token = ref('')
  const username = ref('')

  function login(user: string) {
    username.value = user
    token.value = 'demo-token'
    localStorage.setItem('auth_token', token.value)
    localStorage.setItem('auth_user', user)
  }

  function logout(currentPath?: string) {
    if (currentPath) {
      localStorage.setItem(REDIRECT_KEY, currentPath)
    }
    username.value = ''
    token.value = ''
    localStorage.removeItem('auth_token')
    localStorage.removeItem('auth_user')
  }

  function restore() {
    const savedToken = localStorage.getItem('auth_token')
    const savedUser = localStorage.getItem('auth_user')
    if (savedToken && savedUser) {
      token.value = savedToken
      username.value = savedUser
    }
  }

  function getSavedRedirect() {
    return localStorage.getItem(REDIRECT_KEY) || ''
  }

  function clearSavedRedirect() {
    localStorage.removeItem(REDIRECT_KEY)
  }

  return { token, username, login, logout, restore, getSavedRedirect, clearSavedRedirect }
})
