import { get } from '@/core/http/http-client'
import appSettings from '@/core/config/app-settings'

function cdn(path) {
	if (!path) return ''
	if (/^https?:\/\//.test(path)) return path
	if (path.startsWith('//')) return `https:${path}`
	const base = (appSettings.cdnurl || '').replace(/\/$/, '')
	return `${base}${path.startsWith('/') ? path : `/${path}`}`
}

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

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, total: 0 }
}

function unwrapDetailBody(data, raw) {
	if (!data || typeof data !== 'object') data = {}
	if (data.id != null && (data.title != null || data.content != null)) return data
	if (data.data && typeof data.data === 'object' && data.data.id != null) return data.data
	const env = raw?.res?.data ?? raw?.data
	if (env && typeof env === 'object') {
		if (env.id != null) return env
		if (env.data && typeof env.data === 'object' && env.data.id != null) return env.data
	}
	return data
}

function parseImagesField(images) {
	if (Array.isArray(images)) {
		return images.filter(Boolean).map((p) => cdn(p))
	}
	if (typeof images === 'string' && images.trim()) {
		return images
			.split(',')
			.map((s) => s.trim())
			.filter(Boolean)
			.map((p) => cdn(p))
	}
	return []
}

function normalizeScenicRow(item) {
	if (!item || item.id == null) return null
	return {
		id: item.id,
		title: item.title || item.name || '',
		image: cdn(item.image),
		address: item.address || '',
		views: Number(item.views) || 0,
		status: item.status,
		raw: item
	}
}

export async function pullScenicCategories() {
	const { data, raw } = await get('/scenicareacate/list')
	const rows = unwrapList(data).length ? unwrapList(data) : unwrapList(raw && raw.res)
	return rows
		.filter((row) => row && row.id != null && row.status !== 0)
		.sort((a, b) => Number(b.weigh || 0) - Number(a.weigh || 0))
		.map((row) => ({
			id: row.id,
			name: row.name || '',
			weigh: row.weigh
		}))
}

export async function pullScenicAreaPage({ cateId, page = 1, isHot } = {}) {
	const params = { page }
	if (cateId != null && cateId !== '') params.cate_id = cateId
	if (isHot != null && isHot !== '') params.is_hot = isHot
	const { data, raw } = await get('/scenicarea/list', params)
	const body = unwrapListPageBody(data, raw)
	const rows = (Array.isArray(body.data) ? body.data : [])
		.map(normalizeScenicRow)
		.filter(Boolean)
	return {
		rows,
		total: Number(body.total || rows.length),
		currentPage: Number(body.current_page || page || 1),
		lastPage: Number(body.last_page || body.current_page || 1)
	}
}

/** 首页热门景区（is_hot=1） */
export async function pullHotScenicAreas({ page = 1, pageSize = 12 } = {}) {
	const pack = await pullScenicAreaPage({ page, isHot: 1 })
	return pack.rows.slice(0, pageSize)
}

export async function pullScenicAreaDetail(id) {
	const { data, raw } = await get('/scenicarea/detail', { id })
	const detail = unwrapDetailBody(data, raw)
	const gallery = parseImagesField(detail.images)
	const cover = cdn(detail.image)
	return {
		...detail,
		image: cover,
		images: gallery.length ? gallery : cover ? [cover] : [],
		address: detail.address || '',
		content: detail.content || '',
		views: Number(detail.views) || 0
	}
}
