import {
	getlive,
	getLiveViewData,
	currentActivities,
	remainingTime,
	completionRecords
} from '@/api/cacheLiving.js'
import { oncePerSession, clearSessionByPrefix } from './liveRequestGuard.js'

/** 加载直播间详情 */
export function fetchLiveRoom(liveId, refresh = false) {
	return oncePerSession(`live:room:${liveId}`, () => getlive({ id: liveId }), { refresh })
}

/** 点赞/观看/在线人数 */
export function fetchLiveViewData(liveId, refresh = false) {
	return oncePerSession(`live:view:${liveId}`, () => getLiveViewData(liveId), { refresh })
}

/** 红包/抽奖/商品卡/公告快照 */
export function fetchCurrentActivities(liveId, refresh = false) {
	return oncePerSession(`live:activities:${liveId}`, () => currentActivities(liveId), { refresh })
}

/** 完课积分剩余时长 */
export function fetchRemainingTime(liveId, refresh = false) {
	return oncePerSession(`live:remaining:${liveId}`, () => remainingTime({ liveId }), { refresh })
}

/** 用户积分领取记录 */
export function fetchCompletionRecords(liveId, refresh = false) {
	return oncePerSession(`live:completion:${liveId}`, () => completionRecords({ liveId }), { refresh })
}

/** 下拉刷新等场景清除该直播间缓存 */
export function clearLiveRoomRequestCache(liveId) {
	if (!liveId) return
	clearSessionByPrefix(`live:room:${liveId}`)
	clearSessionByPrefix(`live:view:${liveId}`)
	clearSessionByPrefix(`live:activities:${liveId}`)
	clearSessionByPrefix(`live:remaining:${liveId}`)
	clearSessionByPrefix(`live:completion:${liveId}`)
	clearSessionByPrefix(`live:orderUser:${liveId}`)
	clearSessionByPrefix(`live:msg:${liveId}:`)
}

/** 解析 live 接口返回，写入 liveItem 常用字段 */
export function applyLiveRoomResponse(liveItem, res) {
	if (!res || res.code !== 200 || !res.data) {
		return { ok: false, msg: res?.msg || '加载失败' }
	}
	const next = Object.assign({}, liveItem, res.data)
	if (res.serviceTime) {
		next._localTimeWhenReceived = Date.now()
		next.serviceTime = res.serviceTime
	}
	if (res.serviceStartTime) {
		next.serviceStartTime = res.serviceStartTime
	}
	return { ok: true, data: next, storeId: res.storeId, res }
}
