/**
 * passport 表单的纯函数式校验规则集合。
 *
 * 调用方按返回 `{ ok, errorKey, field }` 决定提示与高亮，
 * 文案翻译完全交给消费者，校验层不与 UI 框架/国际化耦合。
 */

const HANDSET_DIGITS = /^\d{5,15}$/
const SECRET_RANGE = { min: 6, max: 20 }

function fail(errorKey, field) {
	return { ok: false, errorKey, field }
}

const OK = Object.freeze({ ok: true })

export function looksLikeHandset(value) {
	const cleaned = String(value || '').replace(/\s+/g, '').replace(/^\+/, '')
	return HANDSET_DIGITS.test(cleaned)
}

export function trimHandset(value) {
	return String(value || '').replace(/\s+/g, '').replace(/^\+/, '')
}

export function secretInRange(value) {
	const v = String(value || '')
	return v.length >= SECRET_RANGE.min && v.length <= SECRET_RANGE.max
}

export function passcodeShape(value) {
	return /^\d{4,6}$/.test(String(value || ''))
}

export function auditSigninForm(form) {
	if (!form || typeof form !== 'object') return fail('passport.err-empty')
	if (!looksLikeHandset(form.handset)) return fail('passport.err-handset', 'handset')
	if (form.mode === 'secret') {
		if (!secretInRange(form.secret)) return fail('passport.err-secret', 'secret')
	} else {
		if (!passcodeShape(form.passcode)) return fail('passport.err-passcode', 'passcode')
	}
	if (!form.accepted) return fail('passport.err-policy', 'accepted')
	return OK
}

export function auditEnrollForm(form) {
	if (!form || typeof form !== 'object') return fail('passport.err-empty')
	if (!looksLikeHandset(form.handset)) return fail('passport.err-handset', 'handset')
	if (!secretInRange(form.secret)) return fail('passport.err-secret', 'secret')
	if (!passcodeShape(form.passcode)) return fail('passport.err-passcode', 'passcode')
	if (!form.accepted) return fail('passport.err-policy', 'accepted')
	return OK
}

export function auditHandset(handset) {
	if (!looksLikeHandset(handset)) return fail('passport.err-handset', 'handset')
	return OK
}
