import { useMutation, useQueryClient } from "@tanstack/react-query";
import { ADMIN_PACKAGES } from "../endpoints";
import { apiPost } from "../../../../../lib/api/methods";
import { errorToast, successToast } from "../../../../../utils/toast";
import { PackageFormData } from "./schema";
import { SUCCESS_MESSAGES } from "./messages";


export default function usePackageCreate() {
  const queryClient = useQueryClient();

  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["create-package"],
    mutationFn: async (data: PackageFormData) => {
      const obj = {
        name: data.name,
        description: data.description,
        price: Number(data.price),
        credits: Number(data.credits),
        isActive: data.isActive === "true",
      };
      const res = await apiPost<{ message: string }>(
        ADMIN_PACKAGES.CREATE_PACKAGE,
        obj,
      );
      return res;
    },
    onSuccess: (data) => {
      successToast(SUCCESS_MESSAGES.CREATE);

      queryClient.invalidateQueries({ queryKey: ["admin-packages"] });
      queryClient.invalidateQueries({ queryKey: ["packages"] });
    },
    onError: (error: any) => {
      errorToast(error?.response?.data?.message ?? "Something went wrong.");
    },
  });

  return { handlePackageCreate: mutateAsync, loading: isPending };
}
