import { get, post } from '@/core/http/http-client'
import { buildRestPath } from '@/core/config/api-paths'
import { extractBroadcastPage, extractBroadcastRows } from '@/features/live/list-normalize'

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

/**
 * 兼容拦截器解包前后两种结构：
 *   A. `{ state, liveurl, ... }`            已解包
 *   B. `{ code:1, msg, data: { state, ... } }` 仍带 envelope
 * 命中 `state/liveurl/recordurl` 任一字段视为已是业务对象。
 */
function unwrapBroadcast(raw) {
	if (!raw || typeof raw !== 'object') return null
	const looksLikeRoom = (obj) =>
		obj && typeof obj === 'object'
		&& (
			'state' in obj
			|| 'liveurl' in obj
			|| 'recordurl' in obj
			|| 'liveid' 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
}

export async function pullBroadcastDetail(roomId) {
	const { data, raw } = await get(live('play'), { id: roomId })
	const room = unwrapBroadcast(data)
	if (room) return room
	return unwrapBroadcast(raw?.res) || {}
}

function unwrapBroadcastListPage(data, raw) {
	const pack = extractBroadcastPage(data)
	if (pack.rows.length) return pack
	if (raw?.res) return extractBroadcastPage(raw.res)
	return extractBroadcastPage(data)
}

export async function pullBroadcastCatalog() {
	const { data, raw } = await get(live('livelist'))
	const pack = unwrapBroadcastListPage(data, raw)
	return pack.rows
}

/**
 * 搜索直播间（GET live/livelist?page=&search=）
 * @param {{ page?: number, search?: string }} opts
 */
export async function searchBroadcastCatalog(opts = {}) {
	const page = Number(opts.page) || 1
	const search = String(opts.search || '').trim()
	const params = { page }
	if (search) params.search = search
	const { data, raw } = await get(live('livelist'), params)
	return unwrapBroadcastListPage(data, raw)
}

/**
 * 查询直播间状态（live-lists golive → getLiveStatus）
 * @returns {'0'|'1'|'2'|'3'|null} 0 未开播 1 直播中 2 已结束 3 封禁；失败返回 null
 */
export async function fetchBroadcastStatus(roomId) {
	if (!roomId) return null
	try {
		const { data } = await get(live('getLiveStatus'), { id: roomId })
		const status = data?.status ?? data?.data?.status
		if (status === undefined || status === null) return null
		return String(status)
	} catch (_) {
		return null
	}
}

export async function probeBroadcastAlive(roomId) {
	const status = await fetchBroadcastStatus(roomId)
	if (status === null) return true
	return status === '1'
}

export async function pullTrialSeconds(roomId) {
	const { data, raw } = await get(live('getLastTime'), { id: roomId })
	const candidates = [
		data != null && typeof data === 'object' ? data.data?.last_time : undefined,
		data != null && typeof data === 'object' ? data.last_time : undefined,
		typeof data === 'number' || typeof data === 'string' ? data : undefined,
		raw?.res?.data?.last_time,
		raw?.res?.data?.data?.last_time,
		raw?.data?.last_time,
		raw?.data?.data?.last_time
	]
	for (let i = 0; i < candidates.length; i++) {
		const rawVal = candidates[i]
		if (rawVal === undefined || rawVal === null || rawVal === '') continue
		const n = Number(rawVal)
		if (!Number.isNaN(n)) return n
	}
	return null
}

/**
 * 解锁付费直播
 * POST /wanlshop/pay/unlocklive  body: { liveId }
 */
export async function unlockLiveRoom(liveId) {
	if (liveId == null || liveId === '') throw new Error('直播间参数缺失')
	const { data, raw } = await post('/wanlshop/pay/unlocklive', {
		liveId: String(liveId)
	})
	return { data, raw }
}

export async function notifyRoomExit(groupId) {
	if (!groupId) return
	await get(live('unload'), { group: groupId, type: 'play' })
}

export async function pushRoomComment(groupId, text) {
	if (!groupId || !text) return
	await get(live('send'), { group: groupId, message: text })
}

export async function pushRoomLike(roomId) {
	await get(live('like'), { id: roomId })
}

/**
 * 求讲解（live/seek）
 * @param {string|number} groupId 直播群组 liveid
 * @param {number} goodsIndex 商品序号（从 1 开始）
 */
export async function requestLiveGoodsExplain(groupId, goodsIndex) {
	if (!groupId) return
	await get(live('seek'), {
		group: groupId,
		goods_index: goodsIndex
	})
}

/**
 * 直播间关注（live-room.nvue onShopLike：GET live/follow，user_no + liveid）
 */
export async function followLiveAnchor({ userNo, groupId }) {
	if (!userNo) return
	await get(live('follow'), {
		user_no: userNo,
		group: groupId || ''
	})
}
