/** 统一解析直播详情 / 列表行里的关注态 */

export function normalizeIsFollow(value) {
	if (value === true || value === 1 || value === '1') return 1
	return 0
}

export function pickIsFollowFromDetail(detail) {
	if (!detail || typeof detail !== 'object') return null
	const candidates = [
		detail.isFollow,
		detail.is_follow,
		detail.shop && detail.shop.isFollow,
		detail.shop && detail.shop.is_follow,
		detail.shop && detail.shop.find_user && detail.shop.find_user.isFollow
	]
	for (let i = 0; i < candidates.length; i += 1) {
		const v = candidates[i]
		if (v !== undefined && v !== null) return normalizeIsFollow(v)
	}
	return null
}

/**
 * live/follow 的 user_no 参数（接口字段名仍为 user_no）
 * 优先顶层 user_no（列表 livelist 常见），再 shop.find_user.user_no / user_id / shop.id
 */
export function pickAnchorFollowId(detail) {
	if (!detail || typeof detail !== 'object') return ''
	const topUserNo = String(detail.user_no || detail.userNo || '').trim()
	if (topUserNo) return topUserNo
	const shop = detail.shop || {}
	const findUser = shop.find_user || shop.findUser || {}
	const fromFindUser = String(findUser.user_no || findUser.userNo || '').trim()
	if (fromFindUser) return fromFindUser
	const shopUserNo = String(shop.user_no || shop.userNo || '').trim()
	if (shopUserNo) return shopUserNo
	const userId = detail.user_id != null && detail.user_id !== '' ? String(detail.user_id).trim() : ''
	if (userId) return userId
	const shopId = shop.id != null && shop.id !== '' ? String(shop.id).trim() : ''
	if (shopId) return shopId
	return ''
}

/** @deprecated 使用 pickAnchorFollowId */
export function pickAnchorUserNoFromDetail(detail) {
	return pickAnchorFollowId(detail)
}

export function pickIsFollowFromRow(row) {
	if (!row || typeof row !== 'object') return 0
	const candidates = [
		row.isFollow,
		row.is_follow,
		row.shop && row.shop.isFollow,
		row.shop && row.shop.find_user && row.shop.find_user.isFollow
	]
	for (let i = 0; i < candidates.length; i += 1) {
		const v = candidates[i]
		if (v !== undefined && v !== null) return normalizeIsFollow(v)
	}
	return 0
}

export function pickAnchorUserNoFromRow(row) {
	return pickAnchorFollowId(row)
}
