import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { examTemplateService } from "@/services/exam-template.service";
import { ieltsExamService } from "@/services/ielts-exam.service";
import { customExamService } from "@/services/custom-exam.service";
import type { IELTSExamConfig, ContentPoolFilters, ExamAssignRequest, CustomExamCreateRequest, SaveAsTemplateRequest } from "@/types";

export function useInternationalTemplates() {
  return useQuery({
    queryKey: queryKeys.examTemplates.international,
    queryFn: examTemplateService.listInternational,
  });
}

export function useCustomTemplates() {
  return useQuery({
    queryKey: queryKeys.examTemplates.custom,
    queryFn: examTemplateService.listCustom,
  });
}

export function useCreateIeltsExam() {
  return useMutation({
    mutationFn: (data: IELTSExamConfig) => ieltsExamService.create(data),
  });
}

export function useIeltsSkills(examId: number) {
  return useQuery({
    queryKey: queryKeys.ieltsExam.skills(examId),
    queryFn: () => ieltsExamService.getSkills(examId),
    enabled: !!examId,
  });
}

export function useIeltsContentPool(examId: number, filters: ContentPoolFilters) {
  return useQuery({
    queryKey: queryKeys.ieltsExam.contentPool(examId, filters),
    queryFn: () => ieltsExamService.getContentPool(examId, filters),
    enabled: !!examId,
  });
}

export function useIeltsAutoAssemble() {
  return useMutation({
    mutationFn: (examId: number) => ieltsExamService.autoAssemble(examId),
  });
}

export function useIeltsValidation(examId: number) {
  return useQuery({
    queryKey: queryKeys.ieltsExam.validation(examId),
    queryFn: () => ieltsExamService.validate(examId),
    enabled: !!examId,
  });
}

export function usePublishIeltsExam() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (examId: number) => ieltsExamService.update(examId, { status: "published" }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["ielts-exam"] }),
  });
}

export function useAssignIeltsExam() {
  return useMutation({
    mutationFn: (data: { examId: number; assignment: ExamAssignRequest }) =>
      ieltsExamService.assign(data.examId, data.assignment),
  });
}

export function useCreateCustomExam() {
  return useMutation({
    mutationFn: (data: CustomExamCreateRequest) => customExamService.create(data),
  });
}

export function useSaveAsTemplate() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: SaveAsTemplateRequest) => examTemplateService.saveCustomTemplate(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.examTemplates.custom }),
  });
}
