
import { create } from 'zustand';
import { dispatcherService } from '../services/dispatcherService';
import { toast } from 'sonner';

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

  fetchData: async () => {
    set({ loading: true, error: null });
    try {
      const result = await dispatcherService.getDispatcherData();
      // Handle potential API variations (e.g. { data: [...] } vs [...])
      const list = Array.isArray(result) ? result : (result?.data || []);
      set({ data: list });
    } catch (error) {
      console.error('Error fetching dispatcher data:', error);
      set({ error: error.message });
      toast.error('Erro ao carregar dados do dispatcher: ' + error.message);
    } finally {
      set({ loading: false });
    }
  }
}));
