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

interface CreateArgs {
  payload: CreateBookingRequestPayload;
  /** Mock-only display aid (ignored by the real client) so the created request renders fully on C5. */
  context?: BookingRequestDisplayContext;
}

/**
 * Creates a booking request (C4 → C5). On success it seeds the new request into the detail cache and
 * invalidates the customer inbox so both reflect it immediately; the page owns the navigation to C5.
 * Domain `400`s (same-gender mismatch, tenancy 404, inactive variant, invalid time/date) surface via
 * `mutation.error` — the fetch layer owns 401/403/5xx toasts.
 */
export function useCreateBookingRequest() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ payload, context }: CreateArgs) => bookingRequestsApi.create(payload, context),
    onSuccess: (dto) => {
      queryClient.setQueryData(bookingRequestKeys.detail(dto.id), dto);
      queryClient.invalidateQueries({ queryKey: bookingRequestKeys.lists() });
    },
  });
}
