"use client";

import { useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { isAuthenticated } from "@/lib/auth/session";
import { resolveAuthenticatedEntryRedirect } from "@/lib/auth/fetchRegisterStatus";

/** اگر توکن معتبر باشد، کاربر را به خانه یا مرحلهٔ درست ثبت‌نام هدایت می‌کند */
export function useAuthSessionRedirect(enabled = true) {
  const router = useRouter();
  const searchParams = useSearchParams();

  useEffect(() => {
    if (!enabled || !isAuthenticated()) return;

    let cancelled = false;
    const redirect = searchParams.get("redirect");

    void resolveAuthenticatedEntryRedirect(redirect).then((target) => {
      if (cancelled || !target) return;
      router.replace(target);
    });

    return () => {
      cancelled = true;
    };
  }, [enabled, router, searchParams]);
}
