import { get, post } from '@/core/http/http-client'
import { fetchUploadConfig, uploadImageFile } from '@/features/dynamics/publish-gateway'
import { parseRealnamePayload } from '@/features/mine-panel/realname-bridge'

const ROUTE_CHECK = '/wanlshop/realname/checkIsReal'
const ROUTE_ADD = '/wanlshop/realname/add'
const ROUTE_DELETE = '/wanlshop/realname/del'

const CN_IDCARD_18 =
	/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/

function pickFields(source) {
	if (!source || typeof source !== 'object') {
		return {
			id: null,
			realname: '',
			idcard: '',
			idcard_front: '',
			idcard_back: ''
		}
	}
	return {
		id: source.id != null && source.id !== '' ? source.id : null,
		realname: source.realname || source.name || '',
		idcard: source.idcard || source.id_card || source.id_number || '',
		idcard_front: source.idcard_front || source.id_card_front || '',
		idcard_back: source.idcard_back || source.id_card_back || ''
	}
}

export function pickRealnameFieldsFromPayload(payload) {
	const { info } = parseRealnamePayload(payload)
	return pickFields(info || payload)
}

export function isValidIdDocumentNumber(raw) {
	const s = String(raw || '').trim()
	if (!s) return false
	if (CN_IDCARD_18.test(s)) return true
	if (s.length < 5 || s.length > 48) return false
	return /^[A-Za-z0-9\s.\/\-–—（）()]+$/.test(s)
}

export function maskIdCard(id) {
	if (!id || typeof id !== 'string') return '-'
	const s = id.trim()
	if (!s) return '-'
	if (CN_IDCARD_18.test(s) && s.length >= 10) {
		return `${s.slice(0, 6)}********${s.slice(-4)}`
	}
	const n = s.length
	if (n <= 4) return '*'.repeat(n)
	if (n <= 8) return `${s.slice(0, 2)}**${s.slice(-2)}`
	return `${s.slice(0, 3)}****${s.slice(-3)}`
}

/** @returns {Promise<{ok:true,is_real:number,info:object|null}|{ok:false,reason:'network'|'api'}>} */
export async function fetchRealnameStatus() {
	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' }
	}
}

export async function submitRealnameApplication(form) {
	const { data, msg } = await post(ROUTE_ADD, {
		realname: form.realname,
		idcard: form.idcard,
		idcard_front: form.idcard_front,
		idcard_back: form.idcard_back
	})
	return { data, msg }
}

export async function removeRealnameRecord(id) {
	const { data, msg } = await post(ROUTE_DELETE, { id })
	return { data, msg }
}

export async function uploadRealnameImage(filePath) {
	const config = await fetchUploadConfig()
	return uploadImageFile(filePath, config)
}
