import { STORAGE } from '@/core/constants/storage-keys'

const PIN_LENGTH = 4

export function isValidTeenPin(pin) {
	return new RegExp(`^\\d{${PIN_LENGTH}}$`).test(String(pin || ''))
}

function normalizeTeenMode(raw) {
	if (raw === null || raw === undefined || raw === '') {
		return { enabled: false, pin: '' }
	}
	if (typeof raw === 'boolean') {
		return { enabled: raw, pin: '' }
	}
	if (typeof raw === 'number') {
		return { enabled: raw === 1, pin: '' }
	}
	if (typeof raw === 'string') {
		try {
			return normalizeTeenMode(JSON.parse(raw))
		} catch (_) {
			return { enabled: false, pin: '' }
		}
	}
	if (typeof raw !== 'object') {
		return { enabled: false, pin: '' }
	}
	const enabled = !!(raw.enabled ?? raw.state ?? raw.isOpen ?? raw.open)
	const pin = String(raw.pin ?? raw.password ?? raw.pwd ?? '')
	return { enabled, pin }
}

export function getStoredTeenMode() {
	try {
		return normalizeTeenMode(uni.getStorageSync(STORAGE.teenMode))
	} catch (_) {}
	return { enabled: false, pin: '' }
}

export function isTeenModeEnabled() {
	return !!getStoredTeenMode().enabled
}

export function verifyTeenPin(pin) {
	const stored = getStoredTeenMode()
	return stored.pin && String(pin || '') === stored.pin
}

export function setStoredTeenMode({ enabled, pin } = {}) {
	const next = {
		enabled: !!enabled,
		pin: enabled ? String(pin || '') : getStoredTeenMode().pin
	}
	if (next.enabled && !isValidTeenPin(next.pin)) return false
	uni.setStorageSync(STORAGE.teenMode, next)
	return true
}

export function enableTeenMode(pin) {
	if (!isValidTeenPin(pin)) return false
	return setStoredTeenMode({ enabled: true, pin })
}

export function disableTeenMode() {
	const stored = getStoredTeenMode()
	return setStoredTeenMode({ enabled: false, pin: stored.pin })
}

export function updateTeenPin(oldPin, newPin) {
	const stored = getStoredTeenMode()
	if (!stored.enabled || stored.pin !== String(oldPin || '')) return false
	if (!isValidTeenPin(newPin)) return false
	return setStoredTeenMode({ enabled: true, pin: newPin })
}
