import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { courseGenerationService } from "@/services/course-generation.service";
import type { CourseConfig, CourseProgress } from "@/types";

export function useGapAnalysis(source: "exam" | "placement", sourceId: number) {
  return useQuery({
    queryKey: queryKeys.courseGeneration.gapAnalysis(source, sourceId),
    queryFn: () => courseGenerationService.getGapAnalysis(source, sourceId),
    enabled: !!sourceId,
  });
}

export function useAutoGenerateCourse() {
  return useMutation({
    mutationFn: (sourceId: number) => courseGenerationService.autoGenerate(sourceId),
  });
}

export function useCreateCourse() {
  return useMutation({
    mutationFn: (data: Partial<CourseConfig>) => courseGenerationService.create(data),
  });
}

export function useCourseDetail(courseId: number) {
  return useQuery({
    queryKey: queryKeys.courseGeneration.course(courseId),
    queryFn: () => courseGenerationService.getCourse(courseId),
    enabled: !!courseId,
  });
}

export function useUpdateCourse() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: { courseId: number; payload: Partial<CourseConfig> }) =>
      courseGenerationService.updateCourse(data.courseId, data.payload),
    onSuccess: (_, vars) => qc.invalidateQueries({ queryKey: queryKeys.courseGeneration.course(vars.courseId) }),
  });
}

export function useTrackProgress() {
  return useMutation({
    mutationFn: (data: { courseId: number; progress: CourseProgress }) =>
      courseGenerationService.trackProgress(data.courseId, data.progress),
  });
}
