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

const ROUTE_APP_CONFIG = '/wanlshop/common/getAppConfig'
const ROUTE_APP_LOGO = '/wanlshop/common/getAppLogo'

/** @param {unknown} raw */
export function unwrapAppConfigPayload(raw) {
	if (!raw || typeof raw !== 'object') return null
	if (raw.appConfig && typeof raw.appConfig === 'object') return raw.appConfig
	if (raw.data && typeof raw.data === 'object') {
		if (raw.data.appConfig && typeof raw.data.appConfig === 'object') {
			return raw.data.appConfig
		}
		return raw.data
	}
	return raw
}

export function resolveRequestLocale() {
	const saved = uni.getStorageSync(STORAGE.language)
	let locale = saved || uni.getLocale() || 'zh-Hant'
	if (locale === 'auto') locale = uni.getLocale() || 'zh-Hant'
	return String(locale).trim() || 'zh-Hant'
}

/**
 * @param {{ lang?: string, version?: string }} [opts]
 */
export async function fetchAppConfig(opts = {}) {
	const lang = opts.lang || resolveRequestLocale()
	const version = opts.version || appSettings.versionName || ''
	const { data, raw } = await get(ROUTE_APP_CONFIG, { lang, version })
	const cfg = unwrapAppConfigPayload(data != null ? data : raw)
	return cfg && typeof cfg === 'object' ? cfg : null
}

export function readCachedAppConfig() {
	try {
		const cached = uni.getStorageSync(STORAGE.appConfig)
		return cached && typeof cached === 'object' ? cached : null
	} catch (_) {
		return null
	}
}

export function persistAppConfig(config) {
	if (!config || typeof config !== 'object') return
	uni.setStorageSync(STORAGE.appConfig, config)
}

/** @returns {Promise<{ logo: string, name: string, email: string }>} */
export async function fetchAppBrand() {
	const { data, raw } = await get(ROUTE_APP_LOGO)
	const payload = unwrapAppConfigPayload(data != null ? data : raw)
	if (!payload || typeof payload !== 'object') {
		return { logo: '', name: '', email: '' }
	}
	return {
		logo: String(payload.logo || '').trim(),
		name: String(payload.name || '').trim(),
		email: String(payload.email || payload.mail || '').trim()
	}
}

/** @returns {Promise<string>} 相对路径，如 /uploads/xxx.png */
export async function fetchAppLogo() {
	const brand = await fetchAppBrand()
	return brand.logo
}
