import appSettings from '@/core/config/app-settings'
import { coerceIceServerList } from '@/platform/webrtc-ice'
import { openPage, openWithLogin, openAnyLink } from '@/core/nav/navigation'
import { detailPageUrl, videoDetailUrl } from '@/features/dynamics/post-media'

export function installGlobalShortcuts(proto) {
	proto.onGoods = (id) => openPage(`/pages/product/goods?id=${id}`)
	proto.orderDetails = (orderId) => openPage(`/pages/user/order/details?id=${orderId}`)
	proto.onShop = (id) => openPage(`/pages/shop/index?id=${id}`)
	proto.onShopGoods = (id) => openPage(`/pages/shop/product/list?shop_id=${id}`)
	proto.onLogistics = (orderId) => openPage(`/pages/user/order/logistics?id=${orderId}`)

	proto.toChat = (shopId, goods = null) => {
		const base = `/pages/notice/chat?shop_id=${shopId}`
		openPage(goods ? `${base}&goods=${JSON.stringify(goods)}` : base)
	}

	proto.onDetails = (id, title) => {
		const raw = id != null ? String(id).trim() : ''
		if (!raw) return
		const encodedTitle = title != null ? String(title) : ''
		if (/^https?:\/\//i.test(raw)) {
			openPage(
				`/pages/article/details?url=${encodeURIComponent(raw)}&title=${encodedTitle}`
			)
			return
		}
		openPage(`/pages/article/details?id=${raw}&title=${encodedTitle}`)
	}

	proto.onAdvert = (data) => {
		if (data.url && !/^https?:\/\//.test(data.url)) {
			openAnyLink(data.url)
		} else {
			openPage(`/pages/article/advert?id=${data.id}`)
		}
	}

	proto.onLive = (id) => openWithLogin(`/pages/apps/find/details/live?id=${id}`)

	proto.$webrtcIceServers = () => {
		const list = appSettings.webrtcIceServers
		if (!Array.isArray(list) || !list.length) return null
		return coerceIceServerList(list)
	}

	proto.onFind = function onFindEntry(data, comments = null) {
		if (data.type === 'live') {
			this.onLive(data.live_id)
			return
		}
		if (data.type === 'video') {
			openPage(videoDetailUrl(data.id, {
				labelId: data.label_id,
				page: data.page,
				compId: data.compID || data.compId,
				orderType: data.order_type,
				isHotDian: data.is_hot_dian
			}))
			return
		}
		const focus = comments ? 'comments' : ''
		openPage(detailPageUrl(data.id, { focus, img: data.img }))
	}
}