import { notFound } from "next/navigation";

import { ReviewReport } from "@/components/review/ReviewReport";
import { fetchProject, fetchReviews } from "@/lib/api/server";
import { latestReview } from "@/lib/review/history";

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

const DEFAULT_CHAPTER_NO = 1;

// 审稿报告页（UX §6.4）。Server Component 取项目 + 审稿留痕历史（新→旧）；
// ReviewReport（Client）承载 SSE 重审 / 裁决 / 验收交互。
export default async function ReviewPage({ params, searchParams }: PageProps) {
  const { id } = await params;
  const { chapter } = await searchParams;
  const chapterNo = parsePositiveInt(chapter) ?? DEFAULT_CHAPTER_NO;
  try {
    const project = await fetchProject(id);
    const history = await fetchReviews(id, chapterNo);
    return (
      <ReviewReport
        project={project}
        chapterNo={chapterNo}
        initialReview={latestReview(history.reviews)}
        initialDraft=""
      />
    );
  } catch {
    notFound();
  }
}

function parsePositiveInt(raw: string | undefined): number | null {
  if (!raw) return null;
  const n = Number.parseInt(raw, 10);
  return Number.isInteger(n) && n > 0 ? n : null;
}
