import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import {
  examReviewService,
  type ExamReviewQueueParams,
} from "@/services/exam-review.service";

import { queryKeys } from "./keys";

export function useExamReviewQueue(params: ExamReviewQueueParams = {}) {
  return useQuery({
    queryKey: queryKeys.exams.reviewQueue(params),
    queryFn: () => examReviewService.queue(params),
  });
}

export function useExamReviewDetail(examId: number | undefined) {
  return useQuery({
    enabled: !!examId,
    queryKey: queryKeys.exams.reviewDetail(examId ?? -1),
    queryFn: () => examReviewService.detail(examId as number),
  });
}

export function useApproveExamReview() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ examId, notes }: { examId: number; notes?: string }) =>
      examReviewService.approve(examId, notes),
    onSuccess: (_data, { examId }) => {
      qc.invalidateQueries({ queryKey: ["exams", "review"] });
      qc.invalidateQueries({ queryKey: queryKeys.exams.reviewDetail(examId) });
    },
  });
}

export function useRejectExamReview() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ examId, notes }: { examId: number; notes: string }) =>
      examReviewService.reject(examId, notes),
    onSuccess: (_data, { examId }) => {
      qc.invalidateQueries({ queryKey: ["exams", "review"] });
      qc.invalidateQueries({ queryKey: queryKeys.exams.reviewDetail(examId) });
    },
  });
}
