import { useAuthStore } from '@/stores/auth-store'
import { createRouter, createWebHistory, type RouteLocationNormalized } from 'vue-router'
import { useProfileStore } from '@/stores/profile-store'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component: () => import('@/pages/LoginPage.vue'),
      meta: { title: 'Login' },
    },
    {
      path: '/',
      component: () => import('@/pages/UserAccountLayout.vue'),
      beforeEnter: onlyAuthenticated,
      children: [
        {
          path: '',
          redirect: '/profiles',
        },
        {
          path: 'me',
          component: () => import('@/pages/MyUserPage.vue'),
          meta: { title: 'My User' },
        },
        {
          path: 'profiles',
          component: () => import('@/pages/ProfilesPage.vue'),
          meta: { title: 'Profiles' },
        },
        {
          path: 'profiles/:name',
          beforeEnter: profileSelected,
          children: [
            {
              path: '',
              component: () => import('@/pages/UserHomePage.vue'),
              meta: { title: (to: RouteLocationNormalized) => 'Profile ' + to.params.name },
            },
            {
              path: 'accounts/:id',
              component: () => import('@/pages/AccountPage.vue'),
              meta: { title: 'Account' },
            },
            {
              path: 'accounts/:id/edit',
              component: () => import('@/pages/forms/EditAccountPage.vue'),
              meta: { title: 'Edit Account' },
            },
            {
              path: 'add-account',
              component: () => import('@/pages/forms/EditAccountPage.vue'),
              meta: { title: 'Add Account' },
            },
            {
              path: 'transactions/:id',
              component: () => import('@/pages/TransactionPage.vue'),
              meta: { title: 'Transaction' },
            },
          ],
        },
      ],
    },
  ],
})

router.beforeEach((to, _, next) => {
  if (to.meta.title !== undefined && typeof to.meta.title === 'string') {
    document.title = 'Finnow - ' + to.meta.title
  } else if (to.meta.title !== undefined && typeof to.meta.title === 'function') {
    document.title = 'Finnow - ' + to.meta.title(to)
  } else {
    document.title = 'Finnow'
  }
  if (import.meta.env.DEV) {
    document.title = '[DEV]' + document.title
  }
  next()
})

function onlyAuthenticated(to: RouteLocationNormalized) {
  const authStore = useAuthStore()
  if (authStore.state) return true
  if (to.path === '/') return '/login'
  return '/login?next=' + encodeURIComponent(to.path)
}

function profileSelected() {
  const profileStore = useProfileStore()
  if (profileStore.state) return true
  return '/profiles' // Send the user to /profiles to select one before continuing.
}

export default router
