import { request, SseConfig } from '@/utils/sse'
import { get } from './request'

export interface Session {
  id: any
  title: string
  updateTime: string
  num: number
  local?: boolean
  messages?: Message[]
}

export interface Message {
  id: any
  role: 'user' | 'ai'
  content: string
  createTime: string
  reasoning?: string | null
}

export interface AiReply {
  type: number
  content: string
}

export type ChatsConfig = Omit<SseConfig, 'onMessage' | 'method'> & {
  onMessage: (reasoningText: string, normalText: string) => void
}

const getSessionsApi = async (): Promise<Session[]> => {
  return await get('/chats')
}

const getMessagesApi = async (sessionId: any): Promise<Message[]> => {
  return await get(`/chats/${sessionId}`)
}

const requestChats = async (method: 'GET' | 'POST', config: ChatsConfig) => {
  // 思考的文字
  let reasoningText = ''
  // 普通文字
  let normalText = ''
  // 请求
  await request({
    ...(config as SseConfig),
    method,
    onMessage: message => {
      // 提取并解析 JSON
      const json = JSON.parse(message)
      if (json.type === 3 || !json.content) return
      if (json.type === 1) {
        // 思考
        reasoningText += json.content
      } else {
        // 普通
        normalText += json.content
      }
      // 更新消息
      config.onMessage(reasoningText, normalText)
    },
  })
}

const postChats = async (config: ChatsConfig) => {
  return await requestChats('POST', config)
}

const getChats = async (config: ChatsConfig) => {
  return await requestChats('GET', config)
}

const chatApi = {
  getSessionsApi,
  getMessagesApi,
  postChats,
  getChats,
}

export default chatApi
