import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import Login from '../views/Login.vue'
import Dashboard from '../views/Dashboard.vue'
import Tasks from '../views/Tasks.vue'
import Logs from '../views/Logs.vue'
import Cameras from '../views/Cameras.vue'
import Models from '../views/Models.vue'
import Reports from '../views/Reports.vue'
import Users from '../views/Users.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/big-screen',
      name: 'big-screen',
      component: Dashboard,
      meta: { requiresAuth: true, showLayout: false }
    },
    {
      path: '/',
      name: 'dashboard',
      component: Dashboard,
      meta: { requiresAuth: true, showLayout: true }
    },
    {
      path: '/cameras',
      name: 'cameras',
      component: Cameras,
      meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
      path: '/models',
      name: 'models',
      component: Models,
      meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
      path: '/tasks',
      name: 'tasks',
      component: Tasks,
      meta: { requiresAuth: true, requiresAdmin: true }
    },
    {
      path: '/logs',
      name: 'logs',
      component: Logs,
      meta: { requiresAuth: true }
    },
    {
      path: '/reports',
      name: 'reports',
      component: Reports,
      meta: { requiresAuth: true }
    },
    {
      path: '/users',
      name: 'users',
      component: Users,
      meta: { requiresAuth: true, requiresAdmin: true }
    }
  ]
})


router.beforeEach((to, _from, next) => {
  const authStore = useAuthStore()

  // Handle external auth callback (e.g. from Simple Auth)
  if (to.query.token && typeof to.query.token === 'string') {
    try {
      const token = decodeURIComponent(to.query.token)
      const rawUsername = (to.query.username as string) || ''
      const username = decodeURIComponent(rawUsername)
      const isSuperuser = to.query.superuser === 'true'
      
      console.log('External auth callback:', { token: '***', username, isSuperuser })
      
      authStore.setToken(token, username, isSuperuser)
      
      // Remove query params to clean URL
      const query = { ...to.query }
      delete query.token
      delete query.username
      delete query.superuser
      
      next({ path: to.path, query, replace: true })
      return
    } catch (e) {
      console.error('Error parsing auth params:', e)
      next('/login')
      return
    }
  }

  if (to.meta.requiresAuth && !authStore.token) {
    next('/login')
  } else if (to.meta.requiresAdmin && !authStore.isSuperuser) {
    next('/') // Redirect non-admins to dashboard
  } else {
    next()
  }
})

export default router

