"use client";

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

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

/**
 * Creates an admin catalog package.
 *
 * Invalidates the whole `catalog` key, not just the admin list — the new
 * package immediately becomes selectable on every provider's services screen,
 * so both cached lists go stale together.
 *
 * The most likely failure is a duplicate name (409); the toast surfaces the
 * backend's message rather than a generic one.
 */
export function useCreatePackage(options?: { onSuccess?: () => void }) {
  const { t } = useTranslation();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (payload: CreateWashPackageRequest) =>
      createPackageApi(payload),
    onSuccess: () => {
      toast.success(t("catalog.toast.created"));
      queryClient.invalidateQueries({ queryKey: queryKeys.catalog.all });
      options?.onSuccess?.();
    },
    onError: (error) => {
      toast.error(getApiErrorMessage(error, t("catalog.toast.saveFailed")));
    },
  });
}
