import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi } from '@/api/auth'
import { userApi } from '@/api/user'
import { tokenManager } from '@/api/client'
import type { User, Device, RegisterRequest } from '@/types'

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

  // 计算属性
  const isLoggedIn = computed(() => !!tokenManager.getAccessToken() && !!user.value)
  const isAdmin = computed(() => device.value?.isAdmin ?? false)

  // 初始化 - 从本地存储恢复状态
  async function init() {
    const token = tokenManager.getAccessToken()
    if (token && !tokenManager.isTokenExpired()) {
      try {
        await fetchUserProfile()
      } catch {
        tokenManager.clearTokens()
      }
    }
  }

  // 获取用户信息
  async function fetchUserProfile() {
    const response = await userApi.getProfile()
    if (response.success && response.data) {
      user.value = response.data
    }
  }

  // 注册
  async function register(data: RegisterRequest) {
    loading.value = true
    try {
      const response = await authApi.register(data)
      return response
    } finally {
      loading.value = false
    }
  }

  // 登录
  async function login(email: string, password: string) {
    loading.value = true
    try {
      const response = await authApi.login(email, password)
      if (response.success) {
        user.value = response.user || null
        device.value = response.device || null
      }
      return response
    } finally {
      loading.value = false
    }
  }

  // 退出
  async function logout() {
    loading.value = true
    try {
      await authApi.logout()
    } finally {
      user.value = null
      device.value = null
      loading.value = false
    }
  }

  // 更新用户信息
  async function updateProfile(data: { userName?: string; avatar?: string }) {
    const response = await userApi.updateProfile(data)
    if (response.success && response.data) {
      user.value = response.data
    }
    return response
  }

  // 修改密码
  async function changePassword(oldPassword: string, newPassword: string) {
    return await userApi.changePassword(oldPassword, newPassword)
  }

  return {
    // 状态
    user,
    device,
    loading,
    // 计算属性
    isLoggedIn,
    isAdmin,
    // 方法
    init,
    fetchUserProfile,
    register,
    login,
    logout,
    updateProfile,
    changePassword
  }
})

