import { get } from '@/core/http/http-client'
import { buildRestPath } from '@/core/config/api-paths'
import { extractFeedPage, normalizeClip } from '@/features/feed/clip-normalize'
import { pickIsFollowFromRow } from '@/features/live/follow-state'

const detailPath = () => buildRestPath('find/find/getDetails')
const listPath = () => buildRestPath('find/find/getList')

function ensureArray(value) {
	if (Array.isArray(value)) return value
	if (typeof value === 'string' && value.trim()) {
		try {
			const parsed = JSON.parse(value)
			if (Array.isArray(parsed)) return parsed
		} catch (_) {}
		return value.split(',').map((s) => s.trim()).filter(Boolean)
	}
	return []
}

/** 关注接口只认 user_no，不用 user_id / shop.id */
function resolveAuthorUserNo(raw = {}) {
	if (raw.user_no != null && String(raw.user_no).trim() !== '') {
		return String(raw.user_no).trim()
	}
	const user = raw.user
	if (user && user.user_no != null && String(user.user_no).trim() !== '') {
		return String(user.user_no).trim()
	}
	const shop = raw.shop || {}
	const findUser = shop.find_user || shop.findUser || {}
	if (findUser.user_no != null && String(findUser.user_no).trim() !== '') {
		return String(findUser.user_no).trim()
	}
	return ''
}

function normalizePost(raw = {}) {
	const base = raw && typeof raw === 'object' ? raw : {}
	const userNo = resolveAuthorUserNo(base)
	return {
		...base,
		user_no: userNo,
		isFollow: pickIsFollowFromRow(base),
		images: ensureArray(base.images),
		goods: ensureArray(base.goods),
		current: Number(base.current || 0)
	}
}

/** 详情接口返回可能是 post 本体，也可能多包一层 data */
function unwrapDetail(payload) {
	if (!payload || typeof payload !== 'object') return {}
	if (payload.id != null) return payload
	if (payload.data && typeof payload.data === 'object') {
		if (payload.data.id != null) return payload.data
	}
	return payload
}

function pickDetailBody(data, raw) {
	const primary = unwrapDetail(data)
	if (primary.id != null) return primary

	const env = raw?.res?.data ?? raw?.data
	if (!env || typeof env !== 'object') return primary

	const fromEnv = unwrapDetail(env)
	if (fromEnv.id != null) return fromEnv

	if (env.data && typeof env.data === 'object') {
		const nested = unwrapDetail(env.data)
		if (nested.id != null) return nested
	}
	return primary
}

/**
 * 动态详情
 * GET /wanlshop/find/find/getDetails?id=
 */
export async function fetchPostDetail(id) {
	const { data, raw } = await get(detailPath(), { id })
	return normalizePost(pickDetailBody(data, raw))
}

/**
 * 同作者更多动态（详情页下方推荐列表）
 * GET /wanlshop/find/find/getList?user_no=&page=&find_id=
 */
export async function fetchAuthorPosts(userNo, page = 1, findId = '') {
	const { data, raw } = await get(listPath(), {
		user_no: userNo,
		page,
		find_id: findId || ''
	})
	let parsed = extractFeedPage(data)
	if (!parsed.rows.length) {
		const envelope = raw?.res?.data ?? raw?.data
		parsed = extractFeedPage(envelope)
	}
	return {
		rows: parsed.rows.map((row) => normalizePost(normalizeClip(row))),
		currentPage: parsed.currentPage,
		lastPage: parsed.lastPage
	}
}
