import { useMutation, useQueryClient } from '@tanstack/react-query';
import { bookingRequestsApi } from '../apis';
import { bookingRequestKeys } from '../keys';

/**
 * Customer cancel — withdraws a request that is still `pending_nurse_response` or
 * `accepted_awaiting_payment` (before paying). Invalidates the lists + the request detail so both inboxes
 * and the C5 reflect the cancellation. A cancel on a terminal request returns `409` via `mutation.error`.
 */
export function useCancelBookingRequest() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => bookingRequestsApi.cancel(id),
    onSuccess: (dto) => {
      queryClient.setQueryData(bookingRequestKeys.detail(dto.id), dto);
      queryClient.invalidateQueries({ queryKey: bookingRequestKeys.lists() });
      queryClient.invalidateQueries({ queryKey: bookingRequestKeys.detail(dto.id) });
    },
  });
}
