import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { studentLeaveService } from "@/services/student-leave.service";
import type { PaginationParams } from "@/types";
import type { StudentLeaveCreateRequest, StudentLeaveType } from "@/types/student-leave";

export function useStudentLeaves(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.studentLeaves.list(params),
    queryFn: () => studentLeaveService.listLeaves(params),
  });
}

export function useStudentLeaveTypes(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.studentLeaveTypes.list(params),
    queryFn: () => studentLeaveService.listLeaveTypes(params),
  });
}

export function useCreateStudentLeave() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: StudentLeaveCreateRequest) => studentLeaveService.createLeave(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.studentLeaves.all }),
  });
}

export function useUpdateStudentLeave() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<StudentLeaveCreateRequest> }) =>
      studentLeaveService.updateLeave(id, data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.studentLeaves.all }),
  });
}

export function useApproveStudentLeave() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => studentLeaveService.approveLeave(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.studentLeaves.all }),
  });
}

export function useRejectStudentLeave() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => studentLeaveService.rejectLeave(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.studentLeaves.all }),
  });
}

export function useCreateStudentLeaveType() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: Pick<StudentLeaveType, "name">) => studentLeaveService.createLeaveType(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.studentLeaveTypes.all }),
  });
}
