import { type ReactNode } from 'react'
import { Navigate } from 'react-router-dom'
import { useQuery } from '@tanstack/react-query'
import { getMe } from '../api/authApi'

interface ProtectedRouteProps {
  children: ReactNode
}

/** Redirects to /login if the current JWT session is not valid. */
export default function ProtectedRoute({ children }: ProtectedRouteProps) {
  const { data, isLoading, isError } = useQuery({
    queryKey: ['auth', 'me'],
    queryFn: getMe,
    retry: false,
  })

  if (isLoading) return <div>Loading...</div>
  if (isError || !data) return <Navigate to="/login" replace />

  return <>{children}</>
}
