import { post } from '@/core/http/http-client'
import { buildRestPath } from '@/core/config/api-paths'

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

/** 系统通知列表（POST wanlshop/article/getList, type: sys） */
export async function fetchSystemNoticePage(page = 1) {
	const { data, raw } = await post(buildRestPath('/article/getList'), {
		page,
		type: 'sys'
	})
	const body = unwrapListPageBody(data, raw)
	const rows = Array.isArray(body.data) ? body.data : []
	return {
		rows,
		total: Number(body.total || rows.length),
		currentPage: Number(body.current_page || page || 1),
		lastPage: Number(body.last_page || body.current_page || 1)
	}
}
