import { liveMsg } from '@/api/cacheLiving.js'
import { oncePerSession } from './liveRequestGuard.js'

const MAX_TALK_ITEMS = 30

/** 拉取历史聊天记录 */
export async function loadHistoryMessages(liveId, pageSize = 30, pageNum = 1, refresh = false) {
	const res = await oncePerSession(
		`live:msg:${liveId}:${pageSize}:${pageNum}`,
		() => liveMsg(liveId, pageSize, pageNum),
		{ refresh }
	)
	if (res.code !== 200) {
		return []
	}
	const rows = Array.isArray(res.rows) ? res.rows : []
	return [...rows].reverse()
}

/** 追加一条消息并限制列表长度 */
export function appendTalkMessage(talklist, message, messageIdCounter) {
	const list = Array.isArray(talklist) ? talklist : []
	const nextCounter = (messageIdCounter || 0) + 1
	const item = { ...message, uniqueId: nextCounter }
	if (message.data) {
		try {
			const msgdata = typeof message.data === 'string' ? JSON.parse(message.data) : message.data
			item.msgId = msgdata.msgId
		} catch (e) {
			// ignore parse error
		}
	}
	list.push(item)
	while (list.length > MAX_TALK_ITEMS) {
		list.splice(0, list.length - MAX_TALK_ITEMS)
	}
	return { talklist: list, messageIdCounter: nextCounter }
}

/** 按 msgId 删除消息 */
export function removeTalkMessageByMsgId(talklist, msgId) {
	const list = Array.isArray(talklist) ? [...talklist] : []
	const index = list.findIndex(item => item.msgId === msgId)
	if (index !== -1) {
		list.splice(index, 1)
	}
	return list
}
