import { redirect } from "next/navigation";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import { api } from "@/lib/convex/api";
import { convexAuthNextjsToken } from "@convex-dev/auth/nextjs/server";

function makeId(): string {
  return typeof crypto.randomUUID === "function"
    ? crypto.randomUUID()
    : `${Date.now()}_${Math.random().toString(16).slice(2)}`;
}

export default async function Home() {
  if (!isConvexEnabled()) {
    redirect("/auth");
  }

  const token = await convexAuthNextjsToken();
  if (!token) {
    redirect("/auth");
  }

  const { auth, client } = await getAuthedConvexClient();

  const { activeWorkspaceId } = await client.mutation(api.workspaces.ensureDefaultWorkspace, {
    fallbackName: auth.name ?? auth.email ?? "我的空间",
    workspaceIdIfCreate: makeId(),
  });

  const docs = await client.query(api.documents.listByWorkspace, {
    workspaceId: activeWorkspaceId,
  });

  const firstDoc = [...docs].sort((a, b) => (a.created_at ?? "").localeCompare(b.created_at ?? ""))[0];
  if (firstDoc?.id) {
    redirect(`/documents/${firstDoc.id}`);
  }

  const docId = makeId();
  await client.mutation(api.documents.create, {
    id: docId,
    workspaceId: activeWorkspaceId,
    parentId: null,
    title: "新页面",
    accessScope: "private",
    content: [],
  });
  redirect(`/documents/${docId}`);
}
