import { defineRouter } from '#q-app/wrappers'
import {
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory
} from 'vue-router'
import routes from './routes'
import { useAuthStore } from 'stores/auth'
import { useProjectsStore } from 'stores/projects'
const tg = window.Telegram?.WebApp

declare module 'vue-router' {
  interface RouteMeta {
    guestOnly?: boolean
    hideBackButton?: boolean
    backRoute?: string
    requiresAuth?: boolean
  }
}

export default defineRouter(function (/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : process.env.VUE_ROUTER_MODE === 'history'
    ? createWebHistory
    : createWebHashHistory

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,
    history: createHistory(process.env.VUE_ROUTER_BASE)
  })

  const publicPath = ['404', 'terms', 'privacy', 'consent', 'settings']

  const authStore = useAuthStore()
  const projectsStore = useProjectsStore()

  Router.beforeEach(async (to) => {
    if (to.name !== 'telegram_only' && sessionStorage.getItem('isTelegram') === 'false') {
      return { name: 'telegram_only', replace: true }
    }

    if (to.name === 'telegram_only') return true
    if (typeof to.name === 'string' && publicPath.includes(to.name)) return true

     if (to.name === 'login')
       return authStore.isAuth ? { name: 'projects', replace: true } : true

    if (to.name === 'agreements') return true
    if (to.name === 'create_account' && !authStore.isAuth) return true
    if (to.name === 'recovery_password' && !authStore.isAuth) return true

    // need for back from external href - 0Auth Storage
    if (to.name === 'storage' && sessionStorage.getItem('fromExternal')) {
      sessionStorage.removeItem('fromExternal')
      window.history.replaceState(null, '', '/projects') 
      window.history.pushState(null, '', '/settings')
      return { name: 'storage' } 
    }

    if (!authStore.isAuth) return { name: 'login', replace: true }
    
    if (to.params.id) {
      if (!projectsStore.isInit) await projectsStore.init()
      if (to.params.id && projectsStore.projectById(Number(to.params.id))) {
        if (projectsStore.currentProjectId !== Number(to.params.id)) {
          projectsStore.setCurrentProjectId(Number(to.params.id))
        }
      } else {
        projectsStore.setCurrentProjectId(null)
        return { name: 'projects' }
      }
    }
  })

  const handleBackButton = async () => {
    const currentRoute = Router.currentRoute.value

    if (currentRoute.meta.backRoute) {
      await Router.push({ name: currentRoute.meta.backRoute })
    } else {
      if (window.history.length > 1) Router.go(-1) 
      else await Router.push({ name: 'projects' })
    }
  }

  Router.afterEach((to) => {
    if (tg) {
      const BackButton = tg?.BackButton
      if (BackButton) {
        BackButton[to.meta.hideBackButton ? 'hide' : 'show']()
        BackButton.offClick(handleBackButton as () => void)
        BackButton.onClick(handleBackButton as () => void)
      }
    }

    if (to.params.id) projectsStore.setLastProjectId(Number(to.params.id))
    if (to.name === 'projects') projectsStore.setLastProjectId(null)
    projectsStore.setCurrentProjectId(to.params.id ? Number(to.params.id) : null)
  })

  return Router
})