import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { TodoService } from '@/services/todo.service';
import type { CreateTodoRequest, UpdateTodoRequest } from '@/types';

export function useTodos(params?: { status?: string; page?: number; limit?: number }) {
  return useQuery({
    queryKey: ['todos', params],
    queryFn: () => TodoService.getUserTodos(params),
  });
}

export function usePendingTodos() {
  return useQuery({
    queryKey: ['todos', 'pending'],
    queryFn: () => TodoService.getPendingTodos(),
  });
}

export function useCompletedTodos() {
  return useQuery({
    queryKey: ['todos', 'completed'],
    queryFn: () => TodoService.getCompletedTodos(),
  });
}

export function useConfirmedTodos() {
  return useQuery({
    queryKey: ['todos', 'confirmed'],
    queryFn: () => TodoService.getConfirmedTodos(),
  });
}

export function useTodo(id: string) {
  return useQuery({
    queryKey: ['todo', id],
    queryFn: () => TodoService.getById(id),
    enabled: !!id,
  });
}

export function useCreateTodo() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: CreateTodoRequest) => TodoService.create(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });
}

export function useUpdateTodo() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UpdateTodoRequest }) =>
      TodoService.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });
}

export function useDeleteTodo() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) => TodoService.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });
}
