import { create } from "zustand";
import { addInvestigationApi, updateInvestigationApi, removeInvestigationApi } from "../services/investigationApi";
import { useMasterDataStore } from "./masterDataStore";
import { AddInvestigationPayload, UpdateInvestigationPayload } from "../types/medicalData";

interface InvestigationState {
    loading: boolean;
    error: string | null;
    addInvestigation:    (payload: AddInvestigationPayload)    => Promise<boolean>;
    updateInvestigation: (payload: UpdateInvestigationPayload) => Promise<boolean>;
    removeInvestigation: (id: string)                          => Promise<boolean>;
}

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

    addInvestigation: async (payload) => {
        try {
            set({ loading: true, error: null });
            await addInvestigationApi(payload);
            await useMasterDataStore.getState().fetchMasterData();
            set({ loading: false });
            return true;
        } catch (error: any) {
            set({ loading: false, error: error?.response?.data?.msg || error?.message || "Failed to add investigation" });
            return false;
        }
    },

    updateInvestigation: async (payload) => {
        try {
            set({ loading: true, error: null });
            await updateInvestigationApi(payload);
            await useMasterDataStore.getState().fetchMasterData();
            set({ loading: false });
            return true;
        } catch (error: any) {
            set({ loading: false, error: error?.response?.data?.msg || error?.message || "Failed to update investigation" });
            return false;
        }
    },

    removeInvestigation: async (id) => {
        try {
            set({ loading: true, error: null });
            await removeInvestigationApi(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 investigation" });
            return false;
        }
    },
}));