import { get } from '@/core/http/http-client'
import { buildRestPath } from '@/core/config/api-paths'
import { fetchRealnameStatus } from '@/features/account/realname-gateway'
import {
	normalizeRealnameFlag,
	shouldOpenRealnameDetail,
	REALNAME_NONE
} from '@/features/mine-panel/realname-bridge'

const ROUTE_CHECK = buildRestPath('user/checkIsCanPush')

function unwrapPushBody(data, raw) {
	const candidates = [data, raw?.data, raw?.res?.data]
	for (const c of candidates) {
		if (!c || typeof c !== 'object') continue
		if (c.is_can_pass != null || c.no_pass_error != null) return c
		if (c.data && typeof c.data === 'object') {
			const inner = c.data
			if (inner.is_can_pass != null || inner.no_pass_error != null) return inner
		}
	}
	return data && typeof data === 'object' ? data : {}
}

function normalizePerm(body) {
	return {
		isCanPass: Number(body.is_can_pass),
		errorMessage: String(body.no_pass_error || '').trim()
	}
}

/** is_can_pass: 0 可发布，1 需实名认证 */
export async function fetchPushPermission() {
	const { data, raw } = await get(ROUTE_CHECK)
	return normalizePerm(unwrapPushBody(data, raw))
}

export function canPublishContent(isCanPass) {
	return Number(isCanPass) === 0
}

export async function navigateToRealnameVerify() {
	try {
		const r = await fetchRealnameStatus()
		if (!r.ok) {
			uni.navigateTo({ url: '/pages/account/realname-add' })
			return
		}
		const flag = normalizeRealnameFlag(r.is_real)
		if (flag === REALNAME_NONE) {
			uni.navigateTo({ url: '/pages/account/realname-add' })
			return
		}
		if (shouldOpenRealnameDetail(flag)) {
			uni.navigateTo({ url: '/pages/account/realname-info' })
			return
		}
		uni.navigateTo({ url: '/pages/account/realname-add' })
	} catch (_) {
		uni.navigateTo({ url: '/pages/account/realname-add' })
	}
}

export function showPushBlockedModal(vm, perm) {
	const t = vm && vm.$t ? vm.$t.bind(vm) : (k) => k
	const content = perm.errorMessage || t('user.publishNeedRealname')
	return new Promise((resolve) => {
		uni.showModal({
			content,
			showCancel: true,
			cancelText: t('user.realnameModalCancel'),
			confirmText: t('user.publishGoVerify'),
			success: (res) => {
				if (res.confirm) navigateToRealnameVerify()
				resolve(false)
			},
			fail: () => resolve(false)
		})
	})
}

/**
 * 进入发布页时检测：有权限不打扰，无权限弹窗提示。
 */
export async function checkPushPermissionOnEnter(vm) {
	const t = vm && vm.$t ? vm.$t.bind(vm) : (k) => k
	try {
		const perm = await fetchPushPermission()
		if (canPublishContent(perm.isCanPass)) return true
		await showPushBlockedModal(vm, perm)
		return false
	} catch (err) {
		if (vm && vm.$appKit && vm.$appKit.msg) {
			vm.$appKit.msg((err && err.message) || t('user.realnameNetworkError'))
		}
		return false
	}
}
