/**
 * 教练端认证状态管理
 * 风格参考 gym-manage-cuit 的 stores/auth.ts
 */

import { reactive } from 'vue'
import { login as loginApi } from '@/api/auth.js'
import { TOKEN_KEY, USER_INFO_KEY, setToken, setRefreshToken, clearAuth } from '@/utils/request.js'

// 使用 reactive 在 Vue3 Uniapp 中做简易状态管理
const state = reactive({
	accessToken: uni.getStorageSync(TOKEN_KEY) || '',
	userInfo: uni.getStorageSync(USER_INFO_KEY) ? JSON.parse(uni.getStorageSync(USER_INFO_KEY)) : null,
	isLoggedIn: !!uni.getStorageSync(TOKEN_KEY)
})

function saveUserInfo(info) {
	state.userInfo = info
	uni.setStorageSync(USER_INFO_KEY, JSON.stringify(info))
}

async function login(username, password) {
	const res = await loginApi({ username, password })
	// 兼容两种响应格式：{ code, message, data } 包裹 或 直接返回 login data
	const data = res.data || res
	state.accessToken = data.accessToken
	state.userInfo = data.userInfo
	state.isLoggedIn = true

	setToken(data.accessToken)
	setRefreshToken(data.refreshToken)
	saveUserInfo(data.userInfo)

	return data
}

function logout() {
	state.accessToken = ''
	state.userInfo = null
	state.isLoggedIn = false
	clearAuth()
}

function getCoachId() {
	return state.userInfo?.id || null
}

export function useAuthStore() {
	return {
		state,
		login,
		logout,
		getCoachId,
		saveUserInfo
	}
}
