import { adminBaseRoutePath } from '/@/router/static/adminBase'

function shouldStripQuestionBeforeHash(): boolean {
    const { search, hash } = window.location
    if (!hash.startsWith('#/')) {
        return false
    }
    if (search === '?') {
        return true
    }
    return window.location.href.includes('/?#/')
}

/** 将 `/?#/path` 规范为 `/#/path` */
export function ensureStandardHashUrl(): void {
    if (typeof window === 'undefined') {
        return
    }
    const { pathname } = window.location
    const onAppRoot = pathname === '/' || pathname === ''
    if (!onAppRoot || !shouldStripQuestionBeforeHash()) {
        return
    }
    const hash = window.location.hash
    window.history.replaceState(window.history.state, '', pathname + hash)
}

/** 根路径无 hash 时跳转到后台登录（`/#/admin/login`） */
export function redirectRootToAdminLoginIfNoHash(): void {
    if (typeof window === 'undefined') {
        return
    }
    const { pathname, hash } = window.location
    const onAppRoot = pathname === '/' || pathname === ''
    if (!onAppRoot || hash) {
        return
    }
    window.location.replace(pathname + '#' + adminBaseRoutePath + '/login')
}
