/**
 * 统一解析 uni.request 回调（兼容拦截器已改写 res 前后的状态）
 */
export function parseApiResponse(res) {
	const httpOk = res.statusCode === 200 && res.errMsg === 'request:ok'
	if (!httpOk) {
		return {
			kind: 'http_error',
			status: res.statusCode,
			message: res.data?.msg,
			res
		}
	}

	const envelope = res.res ?? res.data
	const hasBizEnvelope = envelope && typeof envelope === 'object' && 'code' in envelope

	if (!hasBizEnvelope) {
		return { kind: 'success', data: res.data, message: '', res }
	}

	if (Number(envelope.code) === 1) {
		// 始终从业务 envelope 取 data；勿用 res.data（snapshot 后可能仍是整包 { code, data }）
		const data = envelope.data
		const message = res.msg ?? envelope.msg ?? ''
		return { kind: 'success', data, message, res }
	}

	if (Number(envelope.code) === 4) {
		return { kind: 'silent_fail', message: envelope.msg, res }
	}

	if (envelope.status === 0 || envelope.status === 1) {
		return { kind: 'passthrough', data: envelope, message: envelope.msg ?? '', res }
	}

	return {
		kind: 'biz_fail',
		message: envelope.msg || '请求失败',
		res
	}
}

export function snapshotEnvelope(res) {
	if (res.statusCode === 200 && res.errMsg === 'request:ok' && !res.res) {
		res.res = res.data
	}
}

export function applySuccessPayload(res, parsed) {
	if (parsed.kind !== 'success') return
	if (res.res && res.res.code === 1) {
		res.data = parsed.data
		res.msg = parsed.message
	}
}
