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

const ROUTE_ABOUT = '/wanlshop/common/about'
const ROUTE_UPDATE = '/wanlshop/common/update'

function unwrapAboutPayload(raw) {
	if (!raw || typeof raw !== 'object') return null
	if (raw.data != null && raw.code !== undefined) return raw.data
	return raw
}

/**
 * @param {unknown} value
 * @param {string} defaultId
 */
export function normalizeArticleConfigId(value, defaultId) {
	if (value === undefined || value === null || value === '') return defaultId
	const s = String(value).trim()
	if (s === '') return defaultId
	const n = Number(s)
	if (Number.isFinite(n) && n === 0) return 0
	return s
}

export function isArticleMenuDisabled(id) {
	if (id === undefined || id === null || id === '') return true
	if (id === 0 || id === '0') return true
	const n = Number(String(id).trim())
	return Number.isFinite(n) && n === 0
}

export async function fetchAboutInfo() {
	const { data, raw } = await get(ROUTE_ABOUT)
	const payload = unwrapAboutPayload(data != null ? data : raw)
	if (!payload || typeof payload !== 'object') {
		return {
			name: '88LIVE',
			logo: '',
			copyright: ''
		}
	}
	return {
		name: payload.name || '88LIVE',
		logo: payload.logo || '',
		copyright: payload.copyright || ''
	}
}

export async function probeAppUpdate() {
	const currentCode = Number(appSettings.versionCode)
	const { data } = await get(ROUTE_UPDATE)
	if (!data || Number(data.versionCode) <= currentCode) {
		return { hasUpdate: false, data: null }
	}
	return { hasUpdate: true, data }
}
