import { useMutation, useQueryClient } from '@tanstack/react-query';
import { catalogApi } from '../apis';
import { catalogKeys } from '../keys';
import type { NurseServiceVariant, UpdateVariantInput } from '../types';

/**
 * Edits a variant's price/unit/session/display (the option-set is immutable). On success it primes
 * the single-variant cache with the returned row and invalidates the offerings list — the edited
 * row reflects immediately without a wasteful full refetch of every page.
 */
export function useUpdateVariant() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, input }: { id: number; input: UpdateVariantInput }) => catalogApi.updateVariant(id, input),
    onSuccess: (variant: NurseServiceVariant) => {
      queryClient.setQueryData(catalogKeys.variant(variant.id), variant);
      queryClient.invalidateQueries({ queryKey: catalogKeys.myVariantsLists() });
    },
  });
}
