import { useQuery } from '@tanstack/react-query';
import {
  conversationsApi,
  ConversationQueryParams,
  ConversationDto,
  ConversationListItem,
  MessageDto,
  PaginatedConversations,
  ConversationStatistics,
  AgentExecutionDto,
  AgentStatisticsDto,
  AgentTrendDto,
} from '../infrastructure/conversations.api';

// Conversation list query
export function useConversations(params: ConversationQueryParams) {
  return useQuery<PaginatedConversations>({
    queryKey: ['conversations', 'list', params],
    queryFn: () => conversationsApi.listConversations(params),
  });
}

// Conversations by user query
export function useUserConversations(userId: string, limit = 10, enabled = true) {
  return useQuery<ConversationListItem[]>({
    queryKey: ['conversations', 'by-user', userId, limit],
    queryFn: () => conversationsApi.getConversationsByUser(userId, limit),
    enabled: enabled && !!userId,
  });
}

// Conversation detail query
export function useConversationDetail(id: string, enabled = true) {
  return useQuery<ConversationDto>({
    queryKey: ['conversations', 'detail', id],
    queryFn: () => conversationsApi.getConversation(id),
    enabled: enabled && !!id,
  });
}

// Conversation messages query
export function useConversationMessages(id: string, enabled = true) {
  return useQuery<MessageDto[]>({
    queryKey: ['conversations', 'messages', id],
    queryFn: () => conversationsApi.getConversationMessages(id),
    enabled: enabled && !!id,
  });
}

// Conversation statistics query
export function useConversationStatistics() {
  return useQuery<ConversationStatistics>({
    queryKey: ['conversations', 'statistics'],
    queryFn: () => conversationsApi.getStatistics(),
    refetchInterval: 60000, // Refresh every minute
  });
}

// Agent executions for a specific conversation
export function useConversationAgentExecutions(id: string, enabled = true) {
  return useQuery<AgentExecutionDto[]>({
    queryKey: ['conversations', 'agent-executions', id],
    queryFn: () => conversationsApi.getConversationAgentExecutions(id),
    enabled: enabled && !!id,
  });
}

// Global agent statistics
export function useAgentStatistics(days = 30) {
  return useQuery<AgentStatisticsDto[]>({
    queryKey: ['agent-statistics', days],
    queryFn: () => conversationsApi.getAgentStatistics(days),
  });
}

// Agent trend data
export function useAgentTrend(days = 7, agentType?: string) {
  return useQuery<AgentTrendDto[]>({
    queryKey: ['agent-trend', days, agentType],
    queryFn: () => conversationsApi.getAgentTrend(days, agentType),
  });
}

// Re-export types
export type {
  ConversationDto,
  ConversationListItem,
  ConversationStatus,
  DeviceInfo,
  MessageDto,
  PaginatedConversations,
  ConversationStatistics,
  ConversationQueryParams,
  TokenDetails,
  GlobalTokenStats,
  TodayTokenStats,
  AgentExecutionDto,
  AgentStatisticsDto,
  AgentTrendDto,
} from '../infrastructure/conversations.api';
