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

interface RejectArgs {
  id: number;
  payload: RejectBookingRequestPayload;
}

/**
 * Nurse reject (with a required reason). On success it invalidates every inbox list (the request leaves
 * the pending inbox) and the request detail (the customer's polled C5 shows the rejected terminal card
 * with the reason). A stale reject returns `409` via `mutation.error`.
 */
export function useRejectBookingRequest() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, payload }: RejectArgs) => bookingRequestsApi.reject(id, payload),
    onSuccess: (dto) => {
      queryClient.setQueryData(bookingRequestKeys.detail(dto.id), dto);
      queryClient.invalidateQueries({ queryKey: bookingRequestKeys.lists() });
      queryClient.invalidateQueries({ queryKey: bookingRequestKeys.detail(dto.id) });
    },
  });
}
