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'

declare module 'vue-router' {
  interface RouteMeta {
    public?: boolean
    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()
    
    if (!authStore.isInitialized) {
      await authStore.initialize()
    }

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

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

    if (to.meta.public) {
      return true
    }

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

  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) => {
    const BackButton = window.Telegram?.WebApp?.BackButton
    if (BackButton) {
      BackButton[to.meta.hideBackButton ? 'hide' : 'show']()
      BackButton.offClick(handleBackButton as () => void)
      BackButton.onClick(handleBackButton as () => void)
    }

    if (!to.params.id) {
      useProjectsStore().setCurrentProjectId(null)
    }
  })

  return Router
})