import type { Router } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

export function setupGuards(router: Router) {
  router.beforeEach((to) => {
    // Public routes (marketing pages) — skip auth entirely
    if (to.meta.public) {
      return true
    }

    const auth = useAuthStore()

    // Update org from route param if present
    const org = to.params.org as string | undefined
    if (org && org !== auth.org) {
      auth.setOrg(org)
    }

    // If no user session and auth is enabled, redirect to login page
    if (!auth.isAuthenticated && auth.authEnabled) {
      return { name: 'login', query: org ? { org } : {} }
    }

    // Admin routes require specs:admin permission
    if (to.name === 'admin-indexing' && !auth.hasPermission('specs:admin')) {
      return { name: 'dashboard', params: { org: auth.org } }
    }

    return true
  })
}
