import { create } from 'zustand'
import api from '../api/axios'

export const useEmployeeStore = create((set) => ({
  employees: [],
  loading: false,
  error: null,

  fetchEmployees: async () => {
    set({ loading: true, error: null })
    try {
      const res = await api.get('/employees')
      set({ employees: res.data || [], loading: false })
      return res.data
    } catch (err) {
      set({ loading: false, error: err.message })
      throw err
    }
  },

  createEmployee: async (payload) => {
    set({ loading: true, error: null })
    try {
      const res = await api.post('/employees', payload)
      set({ loading: false })
      return res.data
    } catch (err) {
      set({ loading: false, error: err.message })
      throw err
    }
  },

  updateEmployee: async (id, payload) => {
    set({ loading: true, error: null })
    try {
      const res = await api.put(`/employees/${id}`, payload)
      set({ loading: false })
      return res.data
    } catch (err) {
      set({ loading: false, error: err.message })
      throw err
    }
  },

  deleteEmployee: async (id) => {
    set({ loading: true, error: null })
    try {
      const res = await api.delete(`/employees/${id}`)
      set({ loading: false })
      return res.data
    } catch (err) {
      set({ loading: false, error: err.message })
      throw err
    }
  }
}))

