import { useApi } from './useApi'
import type {
  ConversationDetail,
  ConversationSummary,
  SendResult,
  SuggestChecklistResult,
} from '@/types/ai'
import type { Paginated } from '@/types/pagination'

// AI 요청 타임아웃(ms) — env VITE_AI_TIMEOUT_MS, 백엔드 AI_TIMEOUT_MS 와 동일 값 사용.
// 미설정/비정상이면 기본 60초(AI 생성이 axios 기본 10초를 넘기므로).
const AI_TIMEOUT_MS = Number(import.meta.env.VITE_AI_TIMEOUT_MS) || 60000

// AI 도메인 API Composable — 대화/메시지는 서버(DB)에서 관리(본인 소유 스코프)
export function useAi() {
  const api = useApi()

  async function listConversations(
    page = 1,
    size = 30,
  ): Promise<Paginated<ConversationSummary>> {
    return (await api.get('/ai/conversations', {
      params: { page, size },
    })) as unknown as Paginated<ConversationSummary>
  }

  async function getConversation(id: string): Promise<ConversationDetail> {
    return (await api.get(
      `/ai/conversations/${id}`,
    )) as unknown as ConversationDetail
  }

  // 새 대화 시작(첫 메시지)
  async function startConversation(content: string): Promise<SendResult> {
    return (await api.post('/ai/conversations', {
      content,
    })) as unknown as SendResult
  }

  // 기존 대화에 메시지 추가
  async function sendMessage(id: string, content: string): Promise<SendResult> {
    return (await api.post(`/ai/conversations/${id}/messages`, {
      content,
    })) as unknown as SendResult
  }

  async function deleteConversation(id: string): Promise<void> {
    await api.delete(`/ai/conversations/${id}`)
  }

  // 할 일(체크리스트) 추천 — 실패는 호출측에서 인라인 처리(silent)
  // AI 생성은 axios 기본 10초를 넘기므로 백엔드와 동일한 AI_TIMEOUT_MS 적용
  async function suggestChecklist(payload: {
    projectId: string
    title: string
    content?: string[]
  }): Promise<SuggestChecklistResult> {
    return (await api.post('/ai/suggest-checklist', payload, {
      silent: true,
      timeout: AI_TIMEOUT_MS,
    })) as unknown as SuggestChecklistResult
  }

  return {
    listConversations,
    getConversation,
    startConversation,
    sendMessage,
    deleteConversation,
    suggestChecklist,
  }
}
