import { create } from "zustand";
import { addMedicineApi, removeMedicineApi } from "../services/medicineApi";
import { useMasterDataStore } from "./masterDataStore";
import { AddMedicinePayload } from "../types/medicalData";

interface MedicineState {
    loading: boolean;
    error: string | null;
    addMedicine: (payload: AddMedicinePayload) => Promise<boolean>;
    removeMedicine: (id: string) => Promise<boolean>;
}

export const useMedicineStore = create<MedicineState>((set) => ({
    loading: false,
    error: null,

    addMedicine: async (payload) => {
        try {
            set({ loading: true, error: null });
            await addMedicineApi(payload);
            await useMasterDataStore.getState().fetchMasterData(); // refresh global store
            set({ loading: false });
            return true;
        } catch (error: any) {
            set({ loading: false, error: error?.response?.data?.msg || error?.message || "Failed to add medicine" });
            return false;
        }
    },

    removeMedicine: async (id) => {
        try {
            set({
                loading: true,
                error: null,
            });

            await removeMedicineApi(id);

            await useMasterDataStore
                .getState()
                .fetchMasterData();

            set({
                loading: false,
            });

            return true;
        } catch (error: any) {
            set({
                loading: false,
                error:
                    error?.response?.data?.msg ||
                    error?.message ||
                    "Failed to remove medicine",
            });

            return false;
        }
    },
}));