import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { adminApi } from '@/api/admin'
import { tokenManager } from '@/api/client'
import type { User } from '@/types'
import { AdminRole } from '@/types'

export const useAuthStore = defineStore('auth', () => {
  const user = ref<User | null>(null)
  const loading = ref(false)

  const isLoggedIn = computed(() => !!tokenManager.getAccessToken() && !tokenManager.isTokenExpired())
  const isAdmin = computed(() => user.value && user.value.role >= AdminRole.Admin)
  const isSuperAdmin = computed(() => user.value?.role === AdminRole.SuperAdmin)

  async function login(email: string, password: string) {
    loading.value = true
    try {
      const response = await adminApi.login(email, password)
      if (response.success && response.user) {
        // 检查是否是管理员
        if (response.user.role < AdminRole.Admin) {
          tokenManager.clearTokens()
          return { success: false, message: '您没有管理员权限' }
        }
        user.value = response.user
      }
      return response
    } finally {
      loading.value = false
    }
  }

  async function logout() {
    loading.value = true
    try {
      await adminApi.logout()
    } finally {
      user.value = null
      loading.value = false
    }
  }

  function setUser(userData: User | null) {
    user.value = userData
  }

  return {
    user,
    loading,
    isLoggedIn,
    isAdmin,
    isSuperAdmin,
    login,
    logout,
    setUser
  }
})

