import { ref } from 'vue'
import { login, isLoggedIn } from '@/api/auth'

const loginReady = ref(false)
let loginPromise = null

export function useLogin() {
	async function waitForLogin() {
		if (loginReady.value) {
			return true
		}

		if (loginPromise) {
			return loginPromise
		}

		const app = getApp()
		if (app && app.globalData && app.globalData.loginPromise) {
			loginPromise = app.globalData.loginPromise
			const result = await loginPromise
			loginReady.value = true
			return result
		}

		loginPromise = doLogin()
		return loginPromise
	}

	async function doLogin() {
		try {
			if (!isLoggedIn()) {
				await login()
			}
			loginReady.value = true
			return true
		} catch (e) {
			console.error('登录失败:', e)
			loginReady.value = true
			return false
		}
	}

	async function ensureLogin() {
		if (isLoggedIn()) {
			loginReady.value = true
			return true
		}
		return waitForLogin()
	}

	return {
		loginReady,
		waitForLogin,
		ensureLogin
	}
}
