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


export default function usePackageEdit() {
  const queryClient = useQueryClient();
  const { mutateAsync, isPending } = useMutation({
    mutationKey: ["package-edit"],
    mutationFn: async ({ id, data }: { id: string; 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 apiPatch(ADMIN_PACKAGES.UPDATE_PACKAGE(id), obj);
      return res;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["admin-packages"] });
      queryClient.invalidateQueries({ queryKey: ["packages"] });
      successToast(SUCCESS_MESSAGES.UPDATE);
    },
    onError: (error: any) => {
      errorToast(error?.response?.data?.message ?? "Something went wrong.");
    },
  });

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