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

/**
 * 从登录响应里提炼真正的用户档案。
 * 多种历史形态在这里收敛，保证后续 spread 永远能拿到 token/id 等关键字段。
 */
function pickUserProfile(payload) {
	if (!payload || typeof payload !== 'object') return {}
	if (payload.userinfo && typeof payload.userinfo === 'object') return payload.userinfo
	if (payload.data && typeof payload.data === 'object' && payload.data.userinfo) return payload.data.userinfo
	if (payload.token || payload.id) return payload
	return {}
}

const defaultState = () => ({
	id: 0,
	isLogin: false,
	username: '',
	nickname: '',
	mobile: '',
	avatar: '',
	level: 0,
	gender: 0,
	area_code: '852',
	birthday: '',
	bio: '',
	money: '0.00',
	score: 0,
	token: '',
	pushs: true,
	shock: true,
	voice: true
})

export default {
	namespaced: true,
	state: defaultState(),
	mutations: {
		apply(state, payload) {
			if (!payload || typeof payload !== 'object') return
			Object.keys(payload).forEach((key) => {
				if (key === 'token') {
					const next = payload.token
					const text = next != null ? String(next).trim() : ''
					// 仅在有有效 token 时写入；已登录时忽略空值，避免资料接口清空令牌
					if (text) state.token = text
					else if (!state.token) state.token = ''
					return
				}
				if (key === 'isLogin') {
					const on = payload.isLogin === true || payload.isLogin === 1 || payload.isLogin === '1'
					if (on) state.isLogin = true
					else if (!state.isLogin) state.isLogin = false
					return
				}
				state[key] = payload[key]
			})
			uni.setStorageSync(STORAGE.user, state)
		},
		reset(state) {
			Object.assign(state, defaultState())
		}
	},
	actions: {
		hydrateFromCache({ commit }) {
			const cached = uni.getStorageSync(STORAGE.user)
			if (cached) commit('apply', cached)
		},
		/**
		 * 写入登录态。允许的 payload 形状：
		 *   - `{ userinfo: {...}, statistics: {...} }`  推荐形态
		 *   - `{ data: { userinfo: {...} } }`           envelope 没拆干净时
		 *   - `{ id, token, nickname, ... }`            老接口扁平形态
		 *
		 * 写完 mutation 之后会再次 `setStorageSync`，确保 isLogin 被持久化
		 * （和源项目 store/modules/user.js 行为一致，避免后续 token 拦截器读不到）。
		 */
		login({ state, commit, dispatch }, payload = {}) {
			const profile = pickUserProfile(payload)
			commit('apply', {
				...profile,
				isLogin: true,
				token: profile.token || state.token,
				pushs: true,
				voice: true,
				shock: true
			})
			if (!state.isLogin) state.isLogin = true
			if (profile.token && !state.token) state.token = profile.token
			uni.setStorageSync(STORAGE.user, state)
			const stats = payload && (payload.statistics || (payload.data && payload.data.statistics))
			if (stats) dispatch('stats/merge', stats, { root: true })
		}
	}
}
