/**
 * AI Chat Service
 * Handles AI chat-related API calls
 */

import { apiClient } from '../client'
import type { ChatMessage, ChatFile } from '@/types/apps/aiChatTypes'

export interface ReferencedTask {
  taskId: string
  source: 'calendar' | 'kanban' | 'todo'
  title: string
}

export interface SendAIMessageRequest {
  content: string
  images?: string[]
  files?: ChatFile[]
  model: 'gpt-4' | 'gpt-3.5' | 'claude' | 'gemini'
  conversationId?: string
}

export interface SendAIMessageResponse {
  message: ChatMessage & {
    id: string
    isSensitive?: boolean
    sensitiveReason?: string
  }
  assistantResponse: {
    id: string
    role: 'assistant'
    content: string
    timestamp: string
    referencedTasks?: ReferencedTask[]
  }
}

export interface Conversation {
  id: string
  title: string
  lastMessage: string
  timestamp: string
  messageCount: number
}

export interface GetAIConversationsResponse {
  conversations: Conversation[]
}

export interface GetAIMessagesResponse {
  messages: (ChatMessage & {
    id: string
    timestamp: string
  })[]
}

export interface AIChatTask {
  id: string
  title: string
  description: string
  deadline: number
  routine: 0 | 1 | 2 | 3 | 4
  tags: string[]
  source: 'calendar' | 'kanban' | 'todo'
  status: string
  priority: 'high' | 'medium' | 'low'
}

export interface GetAIChatTasksResponse {
  tasks: AIChatTask[]
}

export const aiChatService = {
  /**
   * ارسال پیام به AI
   */
  async sendMessage(data: SendAIMessageRequest): Promise<SendAIMessageResponse> {
    return apiClient.post<SendAIMessageResponse>('/api/ai-chat/messages', data)
  },

  /**
   * دریافت تاریخچه مکالمه
   */
  async getConversationMessages(conversationId: string): Promise<(ChatMessage & { id: string; timestamp: string })[]> {
    const response = await apiClient.get<GetAIMessagesResponse>(
      `/api/ai-chat/conversations/${conversationId}/messages`
    )
    return response.messages || []
  },

  /**
   * دریافت لیست مکالمات
   */
  async getConversations(): Promise<Conversation[]> {
    const response = await apiClient.get<GetAIConversationsResponse>('/api/ai-chat/conversations')
    return response.conversations || []
  },

  /**
   * دریافت تسک‌های مرتبط (برای AI Chat)
   */
  async getTasks(source?: 'calendar' | 'kanban' | 'todo', routine?: 0 | 1 | 2 | 3 | 4): Promise<AIChatTask[]> {
    const params = new URLSearchParams()
    if (source) params.append('source', source)
    if (routine !== undefined) params.append('routine', routine.toString())

    const queryString = params.toString()
    const endpoint = `/api/ai-chat/tasks${queryString ? `?${queryString}` : ''}`

    const response = await apiClient.get<GetAIChatTasksResponse>(endpoint)
    return response.tasks || []
  }
}




