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

export const useStatusFrota = create((set, get) => ({
  statusList: [],
  loading: false,
  error: null,

  fetchStatus: async () => {
    set({ loading: true, error: null });
    try {
      const data = await statusService.getStatus();
      set({ statusList: Array.isArray(data) ? data : (data.data || []) });
    } catch (error) {
      set({ error: error.message });
      toast.error('Erro ao carregar status: ' + error.message);
    } finally {
      set({ loading: false });
    }
  },

  createStatus: async (data) => {
    set({ loading: true });
    try {
      await statusService.createStatus(data);
      toast.success('Status atualizado com sucesso!');
      get().fetchStatus();
      return true;
    } catch (error) {
      toast.error('Erro ao atualizar status: ' + error.message);
      return false;
    } finally {
      set({ loading: false });
    }
  },

  updateStatus: async (id, data) => {
    set({ loading: true });
    try {
      await statusService.updateStatus(id, data);
      toast.success('Registro editado com sucesso!');
      get().fetchStatus();
      return true;
    } catch (error) {
      toast.error('Erro ao editar registro: ' + error.message);
      return false;
    } finally {
      set({ loading: false });
    }
  }
}));
