import { http } from '@/utils/request'
import type { ChatMessage, ChatSession } from '@/types'

export interface CreateSessionRequest {
  userId: string
  title?: string
}

export interface CreateSessionResponse {
  id: string
  title: string
  userId: string
  createTime: string
  updateTime: string
  messageCount: number
}

export interface GetSessionsResponse {
  sessions: ChatSession[]
  total: number
}

export interface GetMessagesResponse {
  messages: ChatMessage[]
  total: number
}

// 后端实际返回的会话数据结构
export interface ConversationResponse {
  id: string
  userId: string
  userType: string
  title: string
  type: string
  status: string
  startTime: string
  endTime?: string
  lastActiveTime: string
  messageCount: number
  createTime: string
  updateTime: string
}

/**
 * 聊天API服务
 */
export class ChatApiService {
  
  /**
   * 创建聊天会话
   */
  async createSession(userId: string, title?: string): Promise<ChatSession> {
    try {
      console.log('📝 创建会话API调用:', { userId, title })
      // backend-single: POST /conversation/create
      const response = await http.post<ConversationResponse>('/conversation/create', {
        userId,
        title: title || `对话${Date.now()}`
      })
      console.log('📝 创建会话API响应:', response)

      // 处理HTTP响应的data字段
      const data = (response as any).data || response

      // 转换后端数据格式为前端格式 - 完整匹配ChatSession接口
      return {
        id: data.id,
        title: data.title,
        userId: data.userId || data.user_id,
        userType: data.userType || data.user_type,
        type: data.type,
        status: data.status,
        createTime: data.createTime || data.create_time,
        updateTime: data.updateTime || data.update_time,
        messageCount: data.messageCount || data.message_count || 0,
        startTime: data.startTime || data.start_time,
        endTime: data.endTime || data.end_time,
        lastActiveTime: data.lastActiveTime || data.last_active_time
      }
    } catch (error) {
      console.error('❌ 创建会话失败:', error)
      throw error
    }
  }

  /**
   * 获取用户的所有会话
   */
  async getUserSessions(userId: string): Promise<ChatSession[]> {
    try {
      console.log('📂 获取用户会话API调用:', { userId })
      // backend-single: GET /conversation/page?userId=xxx
      const response = await http.get<any>('/conversation/page', { params: { userId, current: 1, size: 100 } })
      console.log('📂 获取用户会话API响应:', response)

      // 处理HTTP响应的data字段（PageResult）
      const pageData = (response as any).data || response
      const records = pageData.records || []

      // 转换为ChatSession数组
      return records.map((conv: any) => ({
        id: conv.id,
        title: conv.title,
        userId: conv.userId || conv.user_id,
        createTime: conv.createTime || conv.create_time,
        updateTime: conv.updateTime || conv.update_time,
        messageCount: conv.messageCount || conv.message_count || 0
      }))
    } catch (error) {
      console.error('❌ 获取用户会话失败:', error)
      return []
    }
  }

  /**
   * 获取会话的所有消息
   * 注意：后端没有按会话ID获取消息的接口，这里返回空数组
   * 实际的消息加载通过messageApi的接口实现
   */
  async getAllSessionMessages(sessionId: string): Promise<ChatMessage[]> {
    console.log('⚠️ getAllSessionMessages: 后端没有此接口，返回空数组。会话ID:', sessionId)
    console.log('💡 建议使用messageApi.getRecentMessages()或messageApi.getUserMessages()获取消息')

    // 返回空数组，避免404错误
    // 实际的消息加载由messageApi处理
    return []
  }

  /**
   * 删除会话
   */
  async deleteSession(sessionId: string): Promise<void> {
    try {
      console.log('🗑️ 删除会话API调用:', { sessionId })
      // backend-single: DELETE /conversation/delete?id=xxx
      await http.delete('/conversation/delete', { params: { id: sessionId } })
      console.log('✅ 删除会话成功')
    } catch (error) {
      console.error('❌ 删除会话失败:', error)
      throw error
    }
  }

  /**
   * 更新会话标题
   */
  async updateSessionTitle(sessionId: string, title: string): Promise<void> {
    try {
      console.log('✏️ 更新会话标题API调用:', { sessionId, title })
      // backend-single: PUT /conversation/update 传id和title
      await http.put('/conversation/update', { id: sessionId, title })
      console.log('✅ 更新会话标题成功')
    } catch (error) {
      console.error('❌ 更新会话标题失败:', error)
      throw error
    }
  }

  /**
   * 获取最近的消息
   * 注意：这个方法已废弃，请使用messageApi.getRecentMessages()
   */
  async getRecentMessages(params: { limit?: number } = {}): Promise<ChatMessage[]> {
    try {
      console.log('⚠️ getRecentMessages: 此方法已废弃，请使用messageApi.getRecentMessages()')
      console.log('💡 建议直接调用messageApi.getRecentMessages(limit)')
      console.log('📝 参数:', params)

      // 返回空数组，避免调用不存在的接口
      return []
    } catch (error) {
      console.error('❌ getRecentMessages错误:', error)
      return []
    }
  }

  /**
   * 搜索消息
   * 注意：这个方法已废弃，请使用messageApi.searchUserMessages()
   */
  async searchMessages(keyword: string, sessionId?: string): Promise<ChatMessage[]> {
    try {
      console.log('⚠️ searchMessages: 此方法已废弃，请使用messageApi.searchUserMessages()')
      console.log('💡 建议直接调用messageApi.searchUserMessages(keyword, limit)')
      console.log('📝 参数:', { keyword, sessionId })

      // 返回空数组，避免调用不存在的接口
      return []
    } catch (error) {
      console.error('❌ searchMessages错误:', error)
      return []
    }
  }
}

// 创建聊天API服务实例
export const chatApi = new ChatApiService()

export default chatApi
