/**
 * 搜索接口（参考 e:\\88live\\pages\\page\\search.vue）
 *   GET  /wanlshop/common/searchList
 *   GET  /wanlshop/common/search?search=
 *   POST /wanlshop/common/setSearch
 */

import { get } from '@/core/http/http-client'
import { buildRestPath } from '@/core/config/api-paths'
import { extractFeedPage } from '@/features/feed/clip-normalize'

const findListPath = () => buildRestPath('find/find/getList')

const hotPath = () => buildRestPath('common/searchList')
const suggestPath = () => buildRestPath('common/search')
const recordPath = () => buildRestPath('common/setSearch')

function unwrapArray(payload) {
	if (!payload) return []
	if (Array.isArray(payload)) return payload
	if (Array.isArray(payload.data)) return payload.data
	if (payload.data && Array.isArray(payload.data.data)) return payload.data.data
	return []
}

function unwrapSuggest(payload) {
	if (!payload || typeof payload !== 'object') {
		return { searchList: [], categoryList: [] }
	}
	const body = payload.data && typeof payload.data === 'object' && !Array.isArray(payload.data)
		? payload.data
		: payload
	return {
		searchList: Array.isArray(body.searchList) ? body.searchList : [],
		categoryList: Array.isArray(body.categoryList) ? body.categoryList : []
	}
}

/** 热门搜索词 */
export async function fetchHotSearchList() {
	try {
		const { data, raw } = await get(hotPath())
		return unwrapArray(data).length ? unwrapArray(data) : unwrapArray(raw && raw.res)
	} catch (_) {
		return []
	}
}

/** 输入联想 */
export async function fetchSearchSuggestions(keyword) {
	const { data, raw } = await get(suggestPath(), { search: keyword })
	const parsed = unwrapSuggest(data)
	if (parsed.searchList.length || parsed.categoryList.length) return parsed
	return unwrapSuggest(raw && raw.res)
}

/**
 * 种草搜索列表（参考 pages/apps/find/list.vue）
 * GET find/find/getList  type=works|user  search=  page=
 */
export async function fetchFindSearchPage(page = 1, { search = '', listType = 'works' } = {}) {
	const { data, raw } = await get(findListPath(), {
		type: listType,
		page,
		search: search || ''
	})
	let parsed = extractFeedPage(data)
	if (!parsed.rows.length) {
		const envelope = raw?.res?.data ?? raw?.data
		parsed = extractFeedPage(envelope)
	}
	if (!parsed.rows.length && Array.isArray(raw?.data)) {
		parsed = extractFeedPage(raw.data)
	}
	return parsed
}

/** 上报搜索词（用于热门统计，与参考页一致为 GET） */
export async function recordSearchKeyword(keywords) {
	if (!keywords) return
	try {
		await get(recordPath(), { keywords })
	} catch (_) {}
}
