"use client";

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

import { updatePackageApi } 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 { UpdateWashPackageRequest } from "@/types/catalog";

interface UpdatePackageVariables extends UpdateWashPackageRequest {
  packageId: string;
}

/**
 * Updates an admin catalog package.
 *
 * The package id travels as a mutation variable rather than a hook argument
 * because one dialog edits whichever row was picked — there is no per-row hook
 * instance to bind it to.
 *
 * Widening or narrowing the price range does NOT re-clamp providers who
 * already priced outside it (the backend leaves their rows alone), so the
 * provider list is invalidated too and shows the drift.
 */
export function useUpdatePackage(options?: { onSuccess?: () => void }) {
  const { t } = useTranslation();
  const queryClient = useQueryClient();

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