import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { adaptiveEngineService } from "@/services/adaptive-engine.service";
import type { AdaptiveThresholdSettings } from "@/types";

export function useAdaptiveDashboard() {
  return useQuery({
    queryKey: queryKeys.adaptiveEngine.dashboard,
    queryFn: () => adaptiveEngineService.getDashboard(),
  });
}

export function useAdaptiveStudents(params?: { page?: number; limit?: number }) {
  return useQuery({
    queryKey: queryKeys.adaptiveEngine.students(params as Record<string, unknown> | undefined),
    queryFn: () => adaptiveEngineService.getStudents(params),
  });
}

export function useStudentSignals(studentId: number | undefined) {
  return useQuery({
    queryKey: queryKeys.adaptiveEngine.signals(studentId ?? 0),
    queryFn: () => adaptiveEngineService.getStudentSignals(studentId!),
    enabled: !!studentId && studentId > 0,
  });
}

export function useStudentAbility(studentId: number | undefined) {
  return useQuery({
    queryKey: queryKeys.adaptiveEngine.ability(studentId ?? 0),
    queryFn: () => adaptiveEngineService.getStudentAbility(studentId!),
    enabled: !!studentId && studentId > 0,
  });
}

export function useAdaptiveSettings() {
  return useQuery({
    queryKey: queryKeys.adaptiveEngine.settings,
    queryFn: () => adaptiveEngineService.getSettings(),
  });
}

export function useUpdateAdaptiveSettings() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: AdaptiveThresholdSettings) => adaptiveEngineService.updateSettings(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.adaptiveEngine.settings });
    },
  });
}
