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

interface ModerateReviewVars {
  reviewId: number;
  action: ModerationAction;
  /** Required for `hide`/`reject` (≤ 500); a missing reason is a domain `400` surfaced to `onError`. */
  reason?: string;
}

/**
 * Transition a review (admin/moderator). On success we invalidate the whole moderation queue subtree (the row
 * has moved out of / into a status view) **and** every nurse public list: the server recomputed the affected
 * nurse's `averageRating`/`totalReviews` from source, but that nurse's id isn't reachable from the mutation
 * vars or the result, so we drop all nurse lists rather than compute anything client-side (the client **never**
 * computes the aggregate). Domain 4xx (a missing `reason` on hide/reject) surface to the caller's `onError`, so
 * the moderation dialog keeps its draft.
 */
export function useModerateReview() {
  const queryClient = useQueryClient();
  return useMutation<ModerateReviewResult, unknown, ModerateReviewVars>({
    mutationFn: ({ reviewId, action, reason }) => reviewsApi.moderateReview(reviewId, action, reason),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: reviewKeys.moderationQueues() });
      queryClient.invalidateQueries({ queryKey: reviewKeys.nurseLists() });
    },
  });
}
