import { getUserIdOrNull } from './auth.uts'
import { toLoginWithRedirect, getCurrentPageUrlWithQuery } from '@/utils/authRedirect.uts'

export type EnsureLoginOptions = {
	redirectUrl?: string
	toastTitle?: string
}

export function ensureAnalyticsLogin(opts?: EnsureLoginOptions): boolean {
	const uid = getUserIdOrNull()
	if (uid != null && uid !== '') return true

	const target = (opts?.redirectUrl != null && opts?.redirectUrl?.length > 0)
		? opts?.redirectUrl as string
		: getCurrentPageUrlWithQuery()

	uni.showToast({ title: opts?.toastTitle ?? '请先登录', icon: 'none' })
	toLoginWithRedirect(target)
	return false
}
