import { defineStore } from 'pinia'
import { ref } from 'vue'
import { userApi } from '@/api/userApi'

export const useUserStore = defineStore('user', () => {
  const users = ref([])
  const loading = ref(false)
  const error = ref(null)

  async function fetchUsers() {
    loading.value = true
    error.value = null
    try {
      users.value = await userApi.list()
    } catch (e) {
      error.value = e.message || '목록을 불러오지 못했습니다.'
    } finally {
      loading.value = false
    }
  }

  async function addUser(payload) {
    const created = await userApi.create(payload)
    users.value.unshift(created)
    return created
  }

  async function removeUser(id) {
    await userApi.remove(id)
    users.value = users.value.filter((u) => u.id !== id)
  }

  return { users, loading, error, fetchUsers, addUser, removeUser }
})
