import apiClient from './client'

// 简化的角色信息（用于列表）
export interface CharacterSimple {
  id: number
  name: string
  avatar: string
  description: string
  createdAt: string
  updatedAt: string
}

// 对话列表项（轻量级）
export interface ConversationListItem {
  id: number
  characterId: number
  title: string
  messageCount: number
  tokenCount: number
  createdAt: string
  updatedAt: string
  character?: CharacterSimple
}

export interface Conversation {
  id: number
  userId?: number
  characterId: number
  title: string
  presetId?: number
  worldbookId?: number
  worldbookEnabled: boolean
  aiProvider: string
  model: string
  settings?: Record<string, any>
  messageCount: number
  tokenCount: number
  createdAt: string
  updatedAt: string
}

export interface Message {
  id: number
  conversationId: number
  role: 'user' | 'assistant' | 'system'
  content: string
  tokenCount: number
  createdAt: string
}

export interface CreateConversationRequest {
  characterId: number
  title?: string
  presetId?: number
  worldbookId?: number
  worldbookEnabled?: boolean
  aiProvider?: string
  model?: string
  settings?: Record<string, any>
}

export interface SendMessageRequest {
  content: string
}

export interface ConversationListResponse {
  list: ConversationListItem[]
  total: number
  page: number
  pageSize: number
}

export interface MessageListResponse {
  list: Message[]
  total: number
}

export const conversationApi = {
  // 创建对话
  createConversation: (data: CreateConversationRequest) => {
    return apiClient.post<Conversation>('/app/conversation', data)
  },

  // 获取对话列表
  getConversationList: (params: { page?: number; pageSize?: number }) => {
    return apiClient.get<ConversationListResponse>('/app/conversation', { params })
  },

  // 获取对话详情
  getConversationById: (id: number) => {
    return apiClient.get<Conversation>(`/app/conversation/${id}`)
  },

  // 删除对话
  deleteConversation: (id: number) => {
    return apiClient.delete(`/app/conversation/${id}`)
  },

  // 获取消息列表
  getMessageList: (conversationId: number, params: { page?: number; pageSize?: number }) => {
    return apiClient.get<MessageListResponse>(`/app/conversation/${conversationId}/messages`, { params })
  },

  // 发送消息
  sendMessage: (conversationId: number, data: SendMessageRequest) => {
    return apiClient.post<Message>(`/app/conversation/${conversationId}/message`, data)
  },

  // 更新对话设置
  updateConversationSettings: (conversationId: number, data: {
    settings?: Record<string, any>
    worldbookId?: number
    worldbookEnabled?: boolean
  }) => {
    return apiClient.put(`/app/conversation/${conversationId}/settings`, data)
  },

  // 重新生成最后一条 AI 回复（非流式）
  regenerateMessage: (conversationId: number) => {
    return apiClient.post<Message>(`/app/conversation/${conversationId}/regenerate`)
  },
}
