import { redirect } from "next/navigation";
import { createSupabaseServerClient } from "@/lib/supabase/server";

export default async function Home() {
  const supabase = await createSupabaseServerClient();
  const {
    data: { session },
  } = await supabase.auth.getSession();

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

  const { data: firstDoc } = await supabase
    .from("documents")
    .select("id")
    .eq("user_id", session.user.id)
    .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,
      title: "新页面",
      content: {},
    })
    .select("id")
    .single();

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

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