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

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

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

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

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

  deleteMonitoring: async (id) => {
    if (!window.confirm('Tem certeza que deseja excluir este monitoramento?')) return;
    set({ loading: true });
    try {
      await prafrotService.deleteMonitoring(id);
      toast.success('Monitoramento excluído com sucesso!');
      get().fetchMonitoring();
      return true;
    } catch (error) {
      const friendlyMsg = extractFriendlyMessage(error);
      toast.error(friendlyMsg);
      return false;
    } finally {
      set({ loading: false });
    }
  }
}));



