"use client"

import { useMutation, useQuery } from "@tanstack/react-query"
import { apiClient } from "@/lib/api/client"
import type { AiChatContext } from "@/lib/ai/chat-context"

export type AiConfig = {
  enabled: boolean
  public_path: string
  mcp_url?: string
  embed_default_temporary: boolean
  default_model: string
  enabled_tools: string[]
  chat_sync_enabled: boolean
  models?: { model_id: string; label: string; enabled: boolean }[]
  restrict_models?: boolean
}

export type AiQuota = {
  requests_used_today: number
  requests_limit: number
  tokens_used_month: number
  tokens_limit: number
  requests_remaining: number
  tokens_remaining: number
}

export type AiSessionResponse = {
  session_id: string
  embed_url: string
  token_secret?: string
  temporary: boolean
  mcp_url?: string
  enabled_tools?: string[]
}

export function useAiConfig() {
  return useQuery({
    queryKey: ["ai", "config"],
    queryFn: () => apiClient.get<AiConfig>("/ai/config"),
    staleTime: 60_000,
  })
}

export function useAiQuota(enabled = true) {
  return useQuery({
    queryKey: ["ai", "quota"],
    queryFn: () => apiClient.get<AiQuota>("/ai/quota"),
    enabled,
    staleTime: 30_000,
  })
}

export function useCreateAiSession() {
  return useMutation({
    mutationFn: (context: AiChatContext) =>
      apiClient.post<AiSessionResponse>("/ai/sessions", {
        app: context.app,
        temporary: context.temporary ?? true,
        message_id: context.messageId,
        account_id: context.accountId,
        drive_path: context.drivePath,
        file_id: context.fileId,
        contact_id: context.contactId,
        subject: context.subject,
        snippet: context.snippet,
      }),
  })
}
