import { pickAnchorUserNoFromRow, pickIsFollowFromRow } from '@/features/live/follow-state'

/**
 * 统一解析直播列表接口 payload（兼容拦截器解包前后多种结构）
 */
export function extractBroadcastRows(payload) {
	if (Array.isArray(payload)) return payload
	if (!payload || typeof payload !== 'object') return []
	if (Array.isArray(payload.data)) return payload.data
	if (payload.data && Array.isArray(payload.data.data)) return payload.data.data
	if (Array.isArray(payload.list)) return payload.list
	return []
}

/** 解析直播列表分页（livelist 接口） */
export function extractBroadcastPage(payload) {
	const rows = extractBroadcastRows(payload)
	let currentPage = 1
	let lastPage = 1
	if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
		const body =
			payload.data && typeof payload.data === 'object' && !Array.isArray(payload.data)
				? payload.data
				: payload
		currentPage = Number(body.current_page || body.page || 1) || 1
		lastPage = Number(body.last_page || body.lastPage || currentPage) || currentPage
	}
	return { rows, currentPage, lastPage }
}

export function mapRowToHallCard(row) {
	const id = row.id != null && row.id !== '' ? String(row.id) : ''
	return {
		id,
		title: pickTitle(row),
		cover: row.image || row.thumb || row.cover || '',
		live: String(row.state) === '1' || String(row.status) === '1' || Number(row.state) === 1,
		isFollow: pickIsFollowFromRow(row),
		anchorUserNo: pickAnchorUserNoFromRow(row),
		raw: row
	}
}

function pickTitle(row) {
	const text = row.content || row.title || row.shopname || row.name || row.nickname
	if (!text) return idLabel(row.id)
	const oneLine = String(text).replace(/\s+/g, ' ').trim()
	return oneLine.length > 36 ? `${oneLine.slice(0, 36)}…` : oneLine
}

function idLabel(id) {
	return id ? `直播间 #${id}` : '直播间'
}
