import { create } from 'zustand'
import authService from '../services/authService'

const useAuthStore = create((set) => ({
  user: null,
  isLoading: false,
  login: async (username, password) => {
    set({ isLoading: true })
    try {
      const user = await authService.login(username, password)
      set({ user, isLoading: false })
      return { success: true }
    } catch (error) {
      set({ isLoading: false })
      return { success: false, error: error.response?.data?.detail || '登录失败' }
    }
  },
  logout: async () => {
    try {
      await authService.logout()
    } catch (e) {
      // ignore
    }
    set({ user: null })
  },
  fetchMe: async () => {
    try {
      const user = await authService.me()
      set({ user })
    } catch {
      set({ user: null })
    }
  },
}))

export default useAuthStore