/**
 * 实名认证状态（我的页侧滑设置面板）
 * is_real: 0 未申请, 10 审核中, 20 审核失败, 30 审核成功
 */
import { get } from '@/core/http/http-client'

export const REALNAME_NONE = 0
export const REALNAME_PENDING = 10
export const REALNAME_REJECTED = 20
export const REALNAME_APPROVED = 30

const ROUTE_CHECK = '/wanlshop/realname/checkIsReal'

export function normalizeRealnameFlag(v) {
	if (v === '' || v === null || v === undefined) return REALNAME_NONE
	const n = Number(v)
	return Number.isFinite(n) ? n : REALNAME_NONE
}

/** 兼容 http 层整包 { code, data } 或已解包的内层 */
function unwrapRealnameBody(raw) {
	if (!raw || typeof raw !== 'object') return null
	if (raw.code != null && raw.data != null && typeof raw.data === 'object') {
		return raw.data
	}
	return raw
}

function pickIsRealField(body) {
	if (!body || typeof body !== 'object') return undefined
	if (body.is_real != null && body.is_real !== '') return body.is_real
	if (body.isReal != null && body.isReal !== '') return body.isReal
	if (body.status != null && body.status !== '') return body.status
	const info = body.info
	if (info && typeof info === 'object') {
		if (info.is_real != null && info.is_real !== '') return info.is_real
		if (info.isReal != null && info.isReal !== '') return info.isReal
		if (info.status != null && info.status !== '') return info.status
	}
	return undefined
}

export function parseRealnamePayload(raw) {
	const body = unwrapRealnameBody(raw)
	if (!body || typeof body !== 'object') {
		return { is_real: REALNAME_NONE, info: null }
	}
	const is_real = normalizeRealnameFlag(pickIsRealField(body))
	const info = body.info && typeof body.info === 'object' ? body.info : null
	return { is_real, info }
}

export function shouldOpenRealnameDetail(is_real) {
	const n = normalizeRealnameFlag(is_real)
	return n === REALNAME_PENDING || n === REALNAME_APPROVED
}

export function realnameBadgeI18nKey(is_real) {
	const n = normalizeRealnameFlag(is_real)
	if (n === REALNAME_NONE) return 'user.realnameStatusNone'
	if (n === REALNAME_PENDING) return 'user.realnameStatusPending'
	if (n === REALNAME_REJECTED) return 'user.realnameStatusRejected'
	if (n === REALNAME_APPROVED) return 'user.realnameStatusApproved'
	return 'user.realnameStatusNone'
}

/** @returns {'muted'|'pending'|'rejected'|'approved'} */
export function realnameStatusTone(is_real) {
	const n = normalizeRealnameFlag(is_real)
	if (n === REALNAME_PENDING) return 'pending'
	if (n === REALNAME_REJECTED) return 'rejected'
	if (n === REALNAME_APPROVED) return 'approved'
	return 'muted'
}

/** @returns {Promise<{ok:true,is_real:number,info:object|null}|{ok:false,reason:'network'|'api'}>} */
export async function pullRealnameFlagFromApi() {
	try {
		const { data } = await get(ROUTE_CHECK)
		const parsed = parseRealnamePayload(data)
		return { ok: true, is_real: parsed.is_real, info: parsed.info }
	} catch (err) {
		if (err && err.kind === 'NETWORK') {
			return { ok: false, reason: 'network' }
		}
		return { ok: false, reason: 'api' }
	}
}
