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'
import { computed } from 'vue'
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)
  })

  Router.beforeEach(async (to) => {
    const authStore = useAuthStore()
    const projectsStore = useProjectsStore()

    if (to.meta.guestOnly && authStore.isAuth) {
      return { name: 'projects' }
    }

    if (to.meta.requiresAuth && !authStore.isAuth) {
      return { 
        name: 'login',
        replace: true
      }
    }

    if (to.params.id) {
      if (!projectsStore.isInit) await projectsStore.init()

      const currentProjectId = computed(() => projectsStore.currentProjectId)

      if (to.params.id) {
        if (currentProjectId.value !== Number(to.params.id)) {
          if (!projectsStore.projectById(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)
      }
    }

    useProjectsStore().setCurrentProjectId(to.params.id ? Number(to.params.id) : null)
  })

  return Router
})