/**
 * Navigation guards for Vue Router.
 *
 * These guards control access to routes based on authentication state
 * and user profile status (e.g., starter deck selection).
 */
import type { NavigationGuardNext, RouteLocationNormalized } from 'vue-router'

import { useAuthStore } from '@/stores/auth'

/**
 * Guard that requires authentication.
 *
 * Redirects unauthenticated users to /login with a redirect query param
 * so they can be sent back after logging in.
 */
export function requireAuth(
  to: RouteLocationNormalized,
  _from: RouteLocationNormalized,
  next: NavigationGuardNext
): void {
  const auth = useAuthStore()

  if (!auth.isAuthenticated) {
    next({
      path: '/login',
      query: { redirect: to.fullPath },
    })
  } else {
    next()
  }
}

/**
 * Guard that requires guest (unauthenticated) status.
 *
 * Redirects authenticated users away from pages like /login
 * since they don't need to log in again.
 */
export function requireGuest(
  _to: RouteLocationNormalized,
  _from: RouteLocationNormalized,
  next: NavigationGuardNext
): void {
  const auth = useAuthStore()

  if (auth.isAuthenticated) {
    next({ path: '/' })
  } else {
    next()
  }
}

/**
 * Guard that requires starter deck selection.
 *
 * After authentication, users must select a starter deck before
 * accessing the main app. This guard redirects users who haven't
 * selected a starter to /starter.
 *
 * Note: This guard should be used AFTER requireAuth in the guard chain,
 * as it assumes the user is already authenticated.
 */
export function requireStarter(
  to: RouteLocationNormalized,
  _from: RouteLocationNormalized,
  next: NavigationGuardNext
): void {
  const auth = useAuthStore()

  // Skip check if going to starter page or if not authenticated
  if (to.path === '/starter' || !auth.isAuthenticated) {
    next()
    return
  }

  // Check if user has selected starter deck
  // This will be populated after fetching user profile
  if (auth.user && !auth.user.hasStarterDeck) {
    next({ path: '/starter' })
  } else {
    next()
  }
}

/**
 * Route meta type augmentation for TypeScript.
 */
declare module 'vue-router' {
  interface RouteMeta {
    /** Route requires authentication */
    requiresAuth?: boolean
    /** Route requires guest (unauthenticated) status */
    requiresGuest?: boolean
    /** Route requires starter deck selection (implies requiresAuth) */
    requiresStarter?: boolean
    /** Layout to use: 'default' | 'minimal' | 'game' */
    layout?: 'default' | 'minimal' | 'game'
  }
}
