import { useMutation, useQueryClient } from '@tanstack/react-query';
import { reviewsApi } from '../apis';
import { reviewKeys } from '../keys';
import type { CreateReviewRequest, SubmitReviewResult } from '../types';

interface CreateReviewVars {
  bookingId: number;
  body: CreateReviewRequest;
}

/**
 * Submit the one review for a completed booking. On success we invalidate **only** the booking's
 * `eligibility` + `myReviewForBooking` keys — so the CTA flips to the "under review" state at once — and
 * deliberately do **NOT** touch any public nurse-reviews list or aggregate: the new review is
 * `pending_moderation` and must never appear publicly until an admin publishes it. Domain 4xx (`409`
 * already-reviewed, `400` bad rating) surface to the caller's `onError`, which keeps the draft.
 */
export function useCreateReview() {
  const queryClient = useQueryClient();
  return useMutation<SubmitReviewResult, unknown, CreateReviewVars>({
    mutationFn: ({ bookingId, body }) => reviewsApi.createReview(bookingId, body),
    onSuccess: (_result, { bookingId }) => {
      queryClient.invalidateQueries({ queryKey: reviewKeys.eligibility(bookingId) });
      queryClient.invalidateQueries({ queryKey: reviewKeys.myReviewForBooking(bookingId) });
    },
  });
}
