// src/router/index.ts
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import routes from './routes'
import { useAuthStore } from '../stores/auth'

const history =
  import.meta.env.VITE_ROUTER_MODE === 'history'
    ? createWebHistory(import.meta.env.BASE_URL)
    : createWebHashHistory(import.meta.env.BASE_URL)

const router = createRouter({
  history,
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

router.beforeEach(async (to, from, next) => {
  // Auth guard logic
  const authStore = useAuthStore()
  const isAuthenticated = authStore.isAuthenticated
  const publicRoutes = ['/auth/login', '/auth/signup', '/auth/callback'] // Added callback route
  const requiresAuth = !publicRoutes.includes(to.path)

  if (requiresAuth && !isAuthenticated) {
    next({ path: '/auth/login', query: { redirect: to.fullPath } }) // Fixed login path with leading slash
  } else if (!requiresAuth && isAuthenticated) {
    next({ path: '/' })
  } else {
    next()
  }
})

export default router
