import { createRouter, createWebHistory } from 'vue-router'
import { usePhotoboothStore } from '../stores/photoboothStore'

import Home from '../pages/Home.vue'
import Capture from '../pages/Capture.vue'
import Customize from '../pages/Customize.vue'
import Result from '../pages/Result.vue'
import Login from '../pages/Login.vue'
import Signup from '../pages/Signup.vue'
import Account from '../pages/Account.vue'

import { useAuthStore } from '../stores/authStore'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: '/', name: 'home', component: Home },
    { path: '/capture', name: 'capture', component: Capture },
    {
      path: '/customize',
      name: 'customize',
      component: Customize,
      meta: { requiresPhotos: true },
    },
    {
      path: '/result',
      name: 'result',
      component: Result,
      meta: { requiresPhotos: true },
    },
    { path: '/login', name: 'login', component: Login },
    { path: '/signup', name: 'signup', component: Signup },
    { path: '/account', name: 'account', component: Account, meta: { requiresAuth: true } },
  ],
})

router.beforeEach(async (to) => {
  const auth = useAuthStore()

  if (to.meta?.requiresAuth && !auth.isAuthenticated) {
    // Try restore session via refresh-cookie before redirecting.
    await auth.refresh()
    if (!auth.isAuthenticated) {
      return { name: 'login', query: { returnTo: to.fullPath } }
    }
  }

  if (to.meta?.requiresPhotos) {
    const store = usePhotoboothStore()
    if (store.photos.length < 3) {
      return { name: 'home' }
    }
  }

  return true
})

export default router
