"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";

import { deletePackageApi } from "@/lib/api/catalog.api";
import { getApiErrorMessage } from "@/lib/api/error";
import { queryKeys } from "@/lib/constants/query-keys";
import { useTranslation } from "@/hooks/useTranslation";

/**
 * Soft-deletes an admin catalog package.
 *
 * `mutateAsync` is what callers should use from a ConfirmDialog: the dialog
 * awaits it and stays open if it rejects, while the toast below explains why.
 *
 * Providers who already offer the package keep their rows backend-side, but
 * the package vanishes from every listing — hence invalidating the whole
 * `catalog` key rather than only the admin list.
 */
export function useDeletePackage(options?: { onSuccess?: () => void }) {
  const { t } = useTranslation();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (packageId: string) => deletePackageApi(packageId),
    onSuccess: () => {
      toast.success(t("catalog.toast.deleted"));
      queryClient.invalidateQueries({ queryKey: queryKeys.catalog.all });
      options?.onSuccess?.();
    },
    onError: (error) => {
      toast.error(getApiErrorMessage(error, t("catalog.toast.deleteFailed")));
    },
  });
}
