import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { libraryService } from "@/services/library.service";
import type { PaginationParams } from "@/types";
import type { MediaCreateRequest, MediaMovement } from "@/types/library";

type MovementWrite = Partial<
  Omit<MediaMovement, "id" | "media_name" | "student_name" | "faculty_name">
>;

export function useLibraryMedia(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.libraryMedia.list(params),
    queryFn: () => libraryService.listMedia(params),
  });
}

export function useCreateMedia() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: MediaCreateRequest) => libraryService.createMedia(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.libraryMedia.all }),
  });
}

export function useLibraryMovements(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.libraryMovements.list(params),
    queryFn: () => libraryService.listMovements(params),
  });
}

export function useCreateMovement() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: MovementWrite) => libraryService.createMovement(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.libraryMovements.all }),
  });
}

export function useUpdateMovement() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: number; data: MovementWrite }) =>
      libraryService.updateMovement(id, data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.libraryMovements.all }),
  });
}

export function useDeleteMedia() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => libraryService.deleteMedia(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.libraryMedia.all }),
  });
}

export function useReturnMovement() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: number) => libraryService.returnMovement(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.libraryMovements.all }),
  });
}

export function useLibraryCards(params?: PaginationParams) {
  return useQuery({
    queryKey: queryKeys.libraryCards.list(params),
    queryFn: () => libraryService.listCards(params),
  });
}

export function useCreateCard() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: { student_id: number }) => libraryService.createCard(data),
    onSuccess: () => qc.invalidateQueries({ queryKey: queryKeys.libraryCards.all }),
  });
}
