"use client"
import type { Children } from "@/core/types/common";
import { Fragment, useEffect, useRef, type JSX } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import Logger from "@/core/utils/helpers/logger";

interface RedirectWrapperProps extends Children {
  sourceKey: string;
}

/**
 * This wrapper is for detecting when user has been redirecting from the parallel route **OR** we need just redirect user to some target route via Router.
 * It means that we're looking is `sourceKey` exists in the search params and then doing redirect with **replace** type.
 * It handles on the **client-side** due we cannot get access to parallel slot via **server-action/route/middleware**,
 * so we need to use Router to get target page.
 */
export default function RedirectProvider(props: Readonly<RedirectWrapperProps>): JSX.Element {
  const router = useRouter();
  const sp = useSearchParams();
  const redirecting = useRef<boolean>(false);

  useEffect(() => {
    const source = sp.get(props.sourceKey);
    if (source && !redirecting.current) {
      Logger.dev(">>> REDIRECT PROVIDER EFFECT")
      // REPLACE to keep correct history stack without utility route
      redirecting.current = true;
      router.replace(source, { scroll: false });
    }
    // eslint-disable-next-line
  }, [sp]);

  return (
    <Fragment>
      {props.children}
    </Fragment>
  );
}