import { notFound } from "next/navigation";

import { Workbench } from "@/components/workbench/Workbench";
import { fetchDraft, fetchProject } from "@/lib/api/server";
import type { ProjectResponse } from "@/lib/api/types";
import { WORKBENCH_CHAPTER_NO } from "@/lib/workbench/chapter";

interface PageProps {
  params: Promise<{ id: string }>;
}

// 写作工作台页（UX §6.3）。Server Component 取项目 + 当前章已存草稿（GET .../draft，
// 404→null=空编辑器），把正文作为编辑器初值种入，重访时重载已写章节；Workbench
// 负责编辑/流式/保存（流式照常覆盖初值）。
export default async function WritePage({ params }: PageProps) {
  const { id } = await params;

  // 仅当项目确实取不到时才判 404；草稿/瞬时错误不应把整页变成「找不到页面」。
  let project: ProjectResponse;
  try {
    project = await fetchProject(id);
  } catch {
    notFound();
  }

  // 草稿读取失败（后端瞬时错误 / 尚无草稿）→ 空编辑器初值，绝不 404。
  let initialText = "";
  try {
    const draft = await fetchDraft(id, WORKBENCH_CHAPTER_NO);
    initialText = draft?.content ?? "";
  } catch {
    initialText = "";
  }

  return <Workbench project={project} initialText={initialText} />;
}
