import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { IpcClient } from "../ipc/ipc_client";
import type { SmartContextRequest, UpdateSmartContextParams } from "../ipc/ipc_types";

export function useSmartContext(request: SmartContextRequest) {
  return useQuery({
    queryKey: ["smart-context", request.chatId],
    queryFn: async () => {
      const client = IpcClient.getInstance();
      return await client.getSmartContext(request);
    },
    enabled: !!request.chatId,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

export function useUpdateSmartContext() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async (params: UpdateSmartContextParams) => {
      const client = IpcClient.getInstance();
      return await client.updateSmartContext(params);
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({ queryKey: ["smart-context", variables.chatId] });
    },
  });
}

export function useClearSmartContext() {
  const queryClient = useQueryClient();
  
  return useMutation({
    mutationFn: async (chatId: number) => {
      const client = IpcClient.getInstance();
      return await client.clearSmartContext({ chatId });
    },
    onSuccess: (_, chatId) => {
      queryClient.invalidateQueries({ queryKey: ["smart-context", chatId] });
    },
  });
}

export function useSmartContextStats(chatId: number) {
  return useQuery({
    queryKey: ["smart-context-stats", chatId],
    queryFn: async () => {
      const client = IpcClient.getInstance();
      return await client.getSmartContextStats({ chatId });
    },
    enabled: !!chatId,
    staleTime: 2 * 60 * 1000, // 2 minutes
  });
}
