import { create } from "zustand";
import {
    addInstructionApi,
    updateInstructionApi,
    removeInstructionApi,
} from "../services/Instructions";

import { useMasterDataStore } from "./masterDataStore";

import {
    AddInstructionPayload,
    UpdateInstructionPayload,
} from "../types/medicalData";

interface InstructionState {
    loading: boolean;
    error: string | null;

    addInstruction: (
        payload: AddInstructionPayload
    ) => Promise<boolean>;

    updateInstruction: (
        payload: UpdateInstructionPayload
    ) => Promise<boolean>;

    removeInstruction: (
        id: string
    ) => Promise<boolean>;
}

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

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

                await addInstructionApi(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 instruction",
                });

                return false;
            }
        },

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

                await updateInstructionApi(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 instruction",
                });

                return false;
            }
        },

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

                await removeInstructionApi(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 instruction",
                });

                return false;
            }
        },
    }));