import { Navigate, Outlet } from 'react-router-dom';

import { useArticleId } from '../hooks/useArticleId';
import { useGetArticleTree } from '../hooks/useGetArticleTree';
import { useLibraryAccessGuard } from '../hooks/useLibraryAccessGuard';
import { huLibrariesRoutes } from '../routes';

/**
 * @description Layout for `/library/:rootId/child/:childId`.
 * Validates that `childId` is numeric and a descendant of `rootId`; redirects to home otherwise.
 * Normalizes `childId === rootId` to the root article URL. Treats missing tree (e.g. 404) like invalid access.
 */
const ChildArticleLayout = () => {
  const { rootId, childId } = useArticleId();

  const shouldNormalize = !!rootId && !!childId && rootId === childId;

  const {
    data: articleTree,
    isLoading,
    isFetching,
    isFetched,
  } = useGetArticleTree(childId);

  const isFetchSettled = isFetched && !isLoading && !isFetching;
  const isWrongTree = isFetchSettled && (!rootId || articleTree?.id !== rootId);

  useLibraryAccessGuard({
    resetKey: `${rootId}/${childId}`,
    isInvalid: shouldNormalize ? false : !childId || isWrongTree,
  });

  if (shouldNormalize) {
    return (
      <Navigate
        to={huLibrariesRoutes.article(rootId)}
        replace
      />
    );
  }

  return <Outlet />;
};

export default ChildArticleLayout;
