import { get, post } from '@/core/http/http-client'
import { buildRestPath } from '@/core/config/api-paths'

const live = (suffix) => buildRestPath(`live/${suffix}`)

function unwrapRoom(raw) {
	if (!raw || typeof raw !== 'object') return null
	const looksLikeRoom = (obj) =>
		obj &&
		typeof obj === 'object' &&
		('pushurl' in obj || 'liveid' in obj || 'id' in obj || 'state' in obj)
	if (looksLikeRoom(raw)) return raw
	if (looksLikeRoom(raw.data)) return raw.data
	if (raw.data && looksLikeRoom(raw.data.data)) return raw.data.data
	return raw
}

/** 开播（POST live/startLive） */
export async function startBroadcastRoom(payload) {
	const { data, raw } = await post(live('startLive'), payload)
	return unwrapRoom(data) || unwrapRoom(raw?.res) || {}
}

/** 主播端离开/结束推流上报 */
export async function notifyBroadcastUnload(groupId) {
	if (!groupId) return
	await get(live('unload'), { group: groupId, type: 'rtmp' })
}

/** 结束页统计 */
export async function fetchBroadcastEndSummary(roomId) {
	const { data, raw } = await get(live('endLive'), { id: roomId })
	const body = data && typeof data === 'object' ? data : {}
	if (body.data && typeof body.data === 'object') return body.data
	if (raw?.res?.data) return raw.res.data
	return body
}

/** 是否具备开播权限（兼容返回数组或对象） */
export async function fetchBroadcastPermission() {
	const { data, raw } = await get(live('getIsLive'))
	const body = data ?? raw?.res?.data ?? raw?.res ?? []
	if (Array.isArray(body)) return body
	if (body && Array.isArray(body.list)) return body.list
	return []
}
