import { defineStore } from 'pinia'

import type { AdminInfo } from '@/services/api/monisuo-admin.api'

export const useAuthStore = defineStore('auth', () => {
  const isLogin = ref(false)
  const token = ref<string | null>(localStorage.getItem('admin_token'))
  const adminInfo = ref<AdminInfo | null>(
    localStorage.getItem('admin_info')
      ? JSON.parse(localStorage.getItem('admin_info')!)
      : null,
  )

  // 初始化时检查 token
  if (token.value) {
    isLogin.value = true
  }

  function setToken(newToken: string) {
    token.value = newToken
    localStorage.setItem('admin_token', newToken)
    isLogin.value = true
  }

  function setAdminInfo(info: AdminInfo) {
    adminInfo.value = info
    localStorage.setItem('admin_info', JSON.stringify(info))
  }

  function logout() {
    token.value = null
    adminInfo.value = null
    isLogin.value = false
    localStorage.removeItem('admin_token')
    localStorage.removeItem('admin_info')
  }

  return {
    isLogin,
    token,
    adminInfo,
    setToken,
    setAdminInfo,
    logout,
  }
})
