import request from '@/config/axios'
import { fetchEventSource } from '@microsoft/fetch-event-source'
import { config } from '@/config/axios/config'
import { buildSseHeaders, validateSseHandshake } from '@/utils/sse'

export interface ErpAiChatReqVO {
  message: string
  conversationId?: string
  useContext?: boolean
}

export interface ErpAiChatRespVO {
  conversationId: string
  answer: string
}

export const ErpAiApi = {
  chat: async (data: ErpAiChatReqVO) => {
    return await request.post<ErpAiChatRespVO>({ url: '/erp/ai/chat', data })
  },
  chatStream: async ({
    data,
    ctrl,
    onMessage,
    onError,
    onClose
  }: {
    data: ErpAiChatReqVO
    ctrl: AbortController
    onMessage?: (res: ErpAiChatRespVO) => void
    onError?: (...args: any[]) => void
    onClose?: (...args: any[]) => void
  }) => {
    return fetchEventSource(`${config.base_url}/erp/ai/chat/stream`, {
      method: 'post',
      headers: buildSseHeaders(),
      openWhenHidden: true,
      body: JSON.stringify(data),
      signal: ctrl.signal,
      async onopen(response) {
        await validateSseHandshake(response)
      },
      onmessage(msg) {
        if (!msg?.data) {
          return
        }
        const payload = JSON.parse(msg.data)
        if (payload?.code !== 0) {
          throw new Error(payload?.msg || '流式响应失败')
        }
        onMessage?.(payload?.data)
      },
      onerror(err) {
        onError?.(err)
        throw err
      },
      onclose() {
        onClose?.()
      }
    })
  }
}
