import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { gradebookService } from "@/services/gradebook.service";
import type { PaginationParams } from "@/types";
import type { GradingAssignmentCreateRequest } from "@/types/gradebook";

export function useGradebooks(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.gradebooks.list(params),
    queryFn: () => gradebookService.listGradebooks(params),
  });
}

export function useGradebookLines(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.gradebookLines.list(params),
    queryFn: () => gradebookService.listGradebookLines(params),
  });
}

export function useGradingAssignments(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.gradingAssignments.list(params),
    queryFn: () => gradebookService.listGradingAssignments(params),
  });
}

export function useCreateGradingAssignment() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: GradingAssignmentCreateRequest) =>
      gradebookService.createGradingAssignment(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.gradingAssignments.all }),
  });
}

export function useUpdateGradingAssignment() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<GradingAssignmentCreateRequest> }) =>
      gradebookService.updateGradingAssignment(id, data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.gradingAssignments.all }),
  });
}

export function useDeleteGradingAssignment() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => gradebookService.deleteGradingAssignment(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.gradingAssignments.all }),
  });
}
