import { create } from 'zustand';
import { prafrotService } from '../services/prafrotService';
import { toast } from 'sonner';
import { extractFriendlyMessage } from '../utils/errorMessages';

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

  fetchWorkshops: async () => {
    set({ loading: true, error: null });
    try {
      const data = await prafrotService.getWorkshops();
      set({ workshops: Array.isArray(data) ? data : (data.data || []) });
    } catch (error) {
      const friendlyMsg = extractFriendlyMessage(error);
      set({ error: friendlyMsg });
      toast.error(friendlyMsg);
    } finally {
      set({ loading: false });
    }
  },

  createWorkshop: async (payload) => {
    set({ loading: true });
    try {
      await prafrotService.createWorkshop(payload);
      toast.success('Oficina registrada com sucesso!');
      get().fetchWorkshops();
      return true;
    } catch (error) {
      const friendlyMsg = extractFriendlyMessage(error);
      toast.error(friendlyMsg);
      return false;
    } finally {
      set({ loading: false });
    }
  },

  updateWorkshop: async (id, payload) => {
    set({ loading: true });
    try {
      await prafrotService.updateWorkshop(id, payload);
      toast.success('Oficina atualizada com sucesso!');
      get().fetchWorkshops();
      return true;
    } catch (error) {
      const friendlyMsg = extractFriendlyMessage(error);
      toast.error(friendlyMsg);
      return false;
    } finally {
      set({ loading: false });
    }
  },

  deleteWorkshop: async (id) => {
    if (!window.confirm('Tem certeza que deseja excluir esta oficina?')) return;
    set({ loading: true });
    try {
      await prafrotService.deleteWorkshop(id);
      toast.success('Oficina excluída com sucesso!');
      get().fetchWorkshops();
      return true;
    } catch (error) {
      const friendlyMsg = extractFriendlyMessage(error);
      toast.error(friendlyMsg);
      return false;
    } finally {
      set({ loading: false });
    }
  }
}));



