import { get, post } from '@/core/http/http-client'
import { fetchUploadConfig, uploadImageFile } from '@/features/dynamics/publish-gateway'
import appSettings from '@/core/config/app-settings'

const ROUTE_ADD = '/wanlshop/feedback/add'
const ROUTE_LISTS = '/wanlshop/feedback/lists'

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 }
}

export function buildDeviceInfo() {
	const sys = uni.getSystemInfoSync()
	const device = {
		language: sys.language,
		brand: sys.brand,
		model: sys.model,
		system: sys.system
	}
	// #ifdef MP-ALIPAY
	device.platform = 'alipay'
	// #endif
	// #ifdef MP-BAIDU
	device.platform = 'baidu'
	// #endif
	// #ifdef MP-QQ
	device.platform = 'qq'
	// #endif
	// #ifdef MP-TOUTIAO
	device.platform = 'toutiao'
	// #endif
	// #ifdef MP-WEIXIN
	device.platform = 'weixin'
	// #endif
	// #ifdef H5
	device.platform = 'h5'
	// #endif
	// #ifdef APP-PLUS
	device.platform = sys.platform
	try {
		device.version = plus.runtime.version
		device.versionCode = plus.runtime.versionCode
	} catch (_) {}
	// #endif
	return device
}

export async function submitFeedback(payload) {
	const { data, msg } = await post(ROUTE_ADD, payload)
	return { data, msg }
}

function normalizeFeedbackRow(item) {
	if (!item || item.id == null) return null
	let images = item.images
	if (typeof images === 'string') {
		try {
			images = JSON.parse(images)
		} catch (_) {
			images = []
		}
	}
	return {
		...item,
		score: Number(item.score) || 0,
		images: Array.isArray(images) ? images : []
	}
}

export async function fetchFeedbackListPage(page = 1) {
	const { data, raw } = await get(ROUTE_LISTS, { page })
	const body = unwrapListPageBody(data, raw)
	const rows = (Array.isArray(body.data) ? body.data : [])
		.map(normalizeFeedbackRow)
		.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)
	}
}

export async function uploadFeedbackImage(filePath) {
	const config = await fetchUploadConfig()
	return uploadImageFile(filePath, config)
}
