import { useEffect } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { createDocumentCommand } from "@/lib/documents/tree-command-client";

export function SidebarCreateDocumentEntry() {
  const searchParams = useSearchParams();

  useEffect(() => {
    const edit = searchParams.get("edit");
    if (edit !== "1") return;
  }, [searchParams]);

  return null;
}

export async function createDocumentAndOpenEdit(router: ReturnType<typeof useRouter>, parentId: string | null) {
  const payload = await createDocumentCommand(parentId);
  const query = new URLSearchParams();
  const workspaceId = payload.workspace_id ?? null;
  if (workspaceId) query.set("workspaceId", workspaceId);
  const nextQuery = query.toString();
  router.push(nextQuery ? `/documents/${payload.id}?${nextQuery}` : `/documents/${payload.id}`);
}
