import { create } from "zustand";
import { createPrescriptionApi } from "../services/prescriptionApi";
import { CreatePrescriptionPayload } from "../types/prescription";

interface PrescriptionState {
  loading: boolean;
  error: string | null;
  success: boolean;

  createPrescription: (
    payload: CreatePrescriptionPayload
  ) => Promise<any>;
}

export const usePrescriptionStore =
  create<PrescriptionState>((set) => ({
    loading: false,
    error: null,
    success: false,

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

        const response =
          await createPrescriptionApi(payload);

        set({
          loading: false,
          success: true,
        });

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

        throw error;
      }
    },
  }));