// src/hooks/useAuthCheck.ts
import { useEffect } from "react"
import { useNavigate, useLocation } from "react-router-dom"
import { useAuth } from "../context/AuthContext"
import instance from "../api/axiosInstance"

export function useAuthCheck() {
  const { token, logout } = useAuth()
  const navigate = useNavigate()
  const location = useLocation()

  useEffect(() => {
    if (!token) {
      navigate(`/login?next=${location.pathname}`, { replace: true })
      return
    }

    instance
      .get("/auth/me")
      .catch(() => {
        logout()
        navigate(`/login?next=${location.pathname}`, { replace: true })
      })
  }, [token, location.pathname, logout, navigate])
}
