import { AI_AGENT_ID } from '@/common/config.js'
import { get, post } from '@/utils/request.js'
import { streamSseRequest } from '@/utils/sse-stream.js'

/**
 * 查询当前用户的 AI 对话会话列表
 * @param {{
 *   status?: 'active' | 'archived',
 *   chatType?: string,
 *   enterpriseId?: number
 * }} params
 */
export function listConversations(params = {}, options = {}) {
	return get('/conversations', params, options)
}

/**
 * 新建 AI 对话会话
 * @param {{
 *   title?: string,
 *   chatType?: string,
 *   conversationNo?: string,
 *   enterpriseId?: number
 * }} data
 * @returns {Promise<{
 *   id: number,
 *   conversationNo: string,
 *   enterpriseId: number,
 *   title?: string,
 *   chatType: string,
 *   status: string,
 *   lastMessageAt?: string,
 *   createTime?: string
 * }>}
 */
export function createConversation(data = {}, options = {}) {
	return post('/conversations', data, options)
}

/**
 * 查询会话消息列表（按 create_time 正序分页，page=1 为最早消息）
 * @param {number} conversationId
 * @param {{ page?: number, size?: number }} params
 */
export function listConversationMessages(conversationId, params = {}, options = {}) {
	return get(`/conversations/${conversationId}/messages`, params, options)
}

/**
 * 按会话查询全部草稿及成本测算
 * GET /api/v1/mp/conversations/{id}/drafts/cost-comparison
 * 返回 DraftWithCostComparisonResponse[]：草稿详情 + cost_comparison（可为 null）
 * @param {number} conversationId
 */
export function listConversationDraftCostComparisons(conversationId, options = {}) {
	return get(`/conversations/${conversationId}/drafts/cost-comparison`, {}, options)
}

/**
 * 会话内 AI 对话（SSE 流式 + 服务端落库）
 * @param {{
 *   conversationId: number,
 *   message: string,
 *   agentId?: string,
 *   onDelta?: (assembledText: string) => void,
 *   onDone?: (assembledText?: string, cardMeta?: object|null) => void,
 *   onError?: (err: Error) => void
 * }} options
 * @returns {() => void} abort
 */
export function streamConversationChat(options = {}) {
	const {
		conversationId,
		message,
		agentId = AI_AGENT_ID,
		onDelta,
		onDone,
		onError
	} = options

	return streamSseRequest({
		url: `/conversations/${conversationId}/chat`,
		data: { message, disable_thinking: true },
		header: {
			'X-Agent-Id': agentId
		},
		onChunk: (assembledText) => {
			if (onDelta) onDelta(assembledText)
		},
		onDone,
		onError
	})
}
