import { redirect } from "next/navigation";
import { createSupabaseServerClient } from "@/lib/supabase/server";
import { ensureDefaultWorkspace, resolveActiveWorkspaceId } from "@/lib/workspaces";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { requireAuthContext } from "@/lib/auth/authContext";
import { getConvexHttpClient } from "@/lib/convex/server";
import { api } from "@/lib/convex/api";

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()) {
    const auth = await requireAuthContext();
    const client = getConvexHttpClient();

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

    const docs = await client.query(api.documents.listByWorkspace, {
      userId: auth.userId,
      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, {
      userId: auth.userId,
      id: docId,
      workspaceId: activeWorkspaceId,
      parentId: null,
      title: "新页面",
      accessScope: "private",
      content: [],
    });
    redirect(`/documents/${docId}`);
  }

  const supabase = await createSupabaseServerClient();
  const session = (await supabase.auth.getSession()).data.session;

  if (!session) {
    redirect("/login");
  }

  await ensureDefaultWorkspace(supabase, session.user.id, session.user.email ?? "我的空间");
  const workspaceId = await resolveActiveWorkspaceId(supabase, session.user.id);

  if (!workspaceId) {
    redirect("/login");
  }

  const { data: firstDoc } = await supabase
    .from("documents")
    .select("id")
    .eq("user_id", session.user.id)
    .eq("workspace_id", workspaceId)
    .order("created_at", { ascending: true })
    .limit(1)
    .maybeSingle();

  if (firstDoc?.id) {
    redirect(`/documents/${firstDoc.id}`);
  }

  const { data: createdDoc, error } = await supabase
    .from("documents")
    .insert({
      user_id: session.user.id,
      workspace_id: workspaceId,
      title: "新页面",
      content: {},
    })
    .select("id")
    .single();

  if (error || !createdDoc) {
    redirect("/login");
  }

  redirect(`/documents/${createdDoc.id}`);
}
