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

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

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

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

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



