import { ref } from 'vue'

const TOKEN_KEY = 'admin_token'
const USER_KEY = 'admin_user'

const permissions = ref([])

export function useAuthStore() {
  const getToken = () => localStorage.getItem(TOKEN_KEY)
  const getUser = () => {
    try {
      const s = localStorage.getItem(USER_KEY)
      return s ? JSON.parse(s) : null
    } catch {
      return null
    }
  }

  const setToken = (token) => {
    if (token) localStorage.setItem(TOKEN_KEY, token)
    else localStorage.removeItem(TOKEN_KEY)
  }

  const setUser = (user) => {
    if (user) localStorage.setItem(USER_KEY, JSON.stringify(user))
    else localStorage.removeItem(USER_KEY)
  }

  const getPermissions = () => permissions.value
  const setPermissions = (arr) => {
    permissions.value = Array.isArray(arr) ? arr : []
  }

  const logout = () => {
    setToken(null)
    setUser(null)
    setPermissions([])
  }

  const isLoggedIn = () => !!getToken()

  const hasPermission = (key) => {
    if (!key) return true
    const user = getUser()
    if (user && user.role_id === 9527) return true
    return permissions.value.includes(key)
  }

  return {
    getToken,
    getUser,
    setToken,
    setUser,
    getPermissions,
    setPermissions,
    hasPermission,
    logout,
    isLoggedIn
  }
}
