/**
 * 国际区号列表：从后端拉取，失败时回退到本地 region-dialcodes 静态表。
 */
import { get } from '@/core/http/http-client'
import { REGION_ROSTER, findRegion as findStaticRegion } from '@/features/passport/region-dialcodes'

const ROUTE_AREA_CODES = '/wanlshop/common/getAreaCode'

let cachedRoster = null
let inflight = null

function stripPlus(code) {
	return String(code || '').trim().replace(/^\+/, '')
}

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

function enrichRow(row) {
	const dial = stripPlus(row.area_code || row.code || row.dial)
	if (!dial) return null
	const id = row.id != null ? String(row.id) : dial
	const title = String(row.title || row.name || '').trim()
	const known = findStaticRegion(dial)
	return Object.freeze({
		slug: `api-${id}`,
		dial,
		flag: known ? known.flag : '🏳️',
		zh: title || (known && known.zh) || dial,
		en: title || (known && known.en) || dial,
		cluster: 'remote',
		sort: Number(row.sort != null ? row.sort : 0)
	})
}

function sortRows(rows) {
	return rows.slice().sort((a, b) => {
		if (a.sort !== b.sort) return a.sort - b.sort
		return Number(a.dial) - Number(b.dial)
	})
}

export function mapApiRows(list) {
	return sortRows(
		normalizeApiList(list)
			.map(enrichRow)
			.filter(Boolean)
	)
}

export function getFallbackRoster() {
	return REGION_ROSTER
}

export function getCachedRoster() {
	return cachedRoster
}

/**
 * 拉取区号列表（带内存缓存，并发请求合并为一次）。
 */
export function fetchDialRegions({ force = false } = {}) {
	if (!force && cachedRoster) {
		return Promise.resolve(cachedRoster)
	}
	if (inflight) return inflight

	inflight = get(ROUTE_AREA_CODES)
		.then(({ data }) => {
			const mapped = mapApiRows(data)
			cachedRoster = mapped.length ? mapped : getFallbackRoster()
			return cachedRoster
		})
		.catch(() => {
			cachedRoster = getFallbackRoster()
			return cachedRoster
		})
		.finally(() => {
			inflight = null
		})

	return inflight
}

export function clearDialRegionCache() {
	cachedRoster = null
	inflight = null
}
