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

const profilePath = (suffix) => buildRestPath(`find/user/${suffix}`)
const findPath = (suffix) => buildRestPath(`find/find/${suffix}`)
const seriesPath = (suffix) => buildRestPath(`videoseries/${suffix}`)

function isProfileCard(obj) {
	return obj && typeof obj === 'object' && (obj.user_no != null || obj.user)
}

/** 同 myuser.vue userInfo 回调里 res.data */
function unwrapProfileCard(data, raw) {
	const candidates = [data, raw?.data, raw?.res?.data]
	for (const c of candidates) {
		if (!isProfileCard(c)) continue
		return c
	}
	if (data?.data && isProfileCard(data.data)) return data.data
	if (raw?.data?.data && isProfileCard(raw.data.data)) return raw.data.data
	return {}
}

/** 同 myuser.vue getList 回调里 res.data（含 data/current_page/last_page） */
function unwrapListPageBody(data, raw) {
	const candidates = [data, raw?.data, raw?.res?.data]
	for (const c of candidates) {
		if (!c || typeof c !== 'object' || Array.isArray(c)) continue
		if (Array.isArray(c.data) || c.current_page != null || c.last_page != null) {
			return c
		}
		if (c.data && typeof c.data === 'object' && !Array.isArray(c.data)) {
			const inner = c.data
			if (Array.isArray(inner.data) || inner.current_page != null) return inner
		}
	}
	return { data: [], current_page: 1, last_page: 1 }
}

/** 用户主页卡片字段规整（isFollow: 1 已关注，0 未关注） */
export function normalizeProfileCard(raw = {}) {
	const base = raw && typeof raw === 'object' ? raw : {}
	const userNo = base.user_no || (base.user && base.user.user_no) || ''
	return {
		...base,
		user_no: userNo,
		isFollow: pickIsFollowFromRow(base)
	}
}

/** 用户主页卡片（POST body 与 myuser 一致：{ id }） */
export async function fetchProfileCard(targetUserId = null) {
	const { data, raw } = await post(profilePath('userInfo'), { id: targetUserId })
	return normalizeProfileCard(unwrapProfileCard(data, raw))
}

/**
 * 作品 / 喜欢列表
 * myuser：type = works ? (isMyfind ? 'myfind' : 'works') : type
 */
export async function fetchProfileContentPage({ tabKey, userNo, page, isOwner }) {
	let type = tabKey
	if (tabKey === 'works' && isOwner) type = 'myfind'
	const { data, raw } = await get(findPath('getList'), {
		type,
		user_no: userNo,
		page
	})
	const body = unwrapListPageBody(data, raw)
	const rows = Array.isArray(body.data) ? body.data : []
	return {
		rows: rows.map(normalizeClip),
		currentPage: Number(body.current_page || page || 1),
		lastPage: Number(body.last_page || body.current_page || 1)
	}
}

/** 粉丝 / 关注列表（POST find/user/getList，type: fans | follow） */
export async function fetchRelationPage({ userNo, listType, page }) {
	const { data, raw } = await post(profilePath('getList'), {
		id: userNo,
		type: listType,
		page
	})
	const body = unwrapListPageBody(data, raw)
	const rows = Array.isArray(body.data) ? body.data : []
	return {
		rows,
		currentPage: Number(body.current_page || page || 1),
		lastPage: Number(body.last_page || body.current_page || 1),
		total: Number(body.total ?? rows.length)
	}
}

/** 合辑列表 */
export async function fetchProfileSeriesPage(userNo, page) {
	const { data, raw } = await get(seriesPath('list'), {
		user_no: userNo,
		page
	})
	const parsed = extractSeriesPage(data)
	if (parsed.rows.length) return parsed
	const envelope = raw?.res?.data ?? raw?.data
	return extractSeriesPage(envelope)
}

/**
 * 把 setFindUser 接口的不一致返回拍平成数字（0 = 取消，1 = 已点赞/关注）。
 */
function unwrapFlag(value) {
	if (value == null) return null
	if (typeof value === 'number') return value
	if (typeof value === 'string') {
		const n = Number(value)
		return Number.isNaN(n) ? null : n
	}
	if (typeof value === 'object') {
		if ('data' in value) return unwrapFlag(value.data)
		if ('isLike' in value) return unwrapFlag(value.isLike)
		if ('isFollow' in value) return unwrapFlag(value.isFollow)
	}
	return null
}

export async function toggleProfileFollow(userNo) {
	const { data } = await post(profilePath('setFindUser'), {
		id: userNo,
		type: 'follow'
	})
	return unwrapFlag(data)
}

export async function toggleProfileLike(contentId) {
	const { data } = await post(profilePath('setFindUser'), {
		id: contentId,
		type: 'likes'
	})
	return unwrapFlag(data)
}

export async function removeProfileContent(contentId) {
	await post(findPath('delData'), { id: contentId })
}

export async function removeProfileSeries(seriesId) {
	await post(seriesPath('del'), { id: seriesId })
}

function parseDiamondValue(payload) {
	if (typeof payload === 'string' || typeof payload === 'number') {
		return Number(payload) || 0
	}
	if (!payload || typeof payload !== 'object') return 0
	if (payload.diamond != null) return Number(payload.diamond) || 0
	if (payload.data != null) return parseDiamondValue(payload.data)
	if (payload.code !== undefined && Number(payload.code) === 1) {
		return parseDiamondValue(payload.data)
	}
	return 0
}

function parseTipWalletValue(payload) {
	if (!payload || typeof payload !== 'object') return '0.00'
	if (payload.data && payload.data.tip_wallet != null) return String(payload.data.tip_wallet)
	if (payload.tip_wallet != null) return String(payload.tip_wallet)
	return '0.00'
}

export async function fetchWalletSnapshot() {
	const [diamondPack, tipPack] = await Promise.all([
		get('/user/getdiamondnum').catch(() => ({ data: 0 })),
		get('/user/gettipwallet').catch(() => ({ data: null }))
	])
	return {
		diamond: parseDiamondValue(diamondPack.data),
		tipWallet: parseTipWalletValue(tipPack.data)
	}
}
