import { NextResponse } from "next/server";
import { isConvexEnabled } from "@/lib/convex/enabled";

type TreeCreateResponse = {
  requestId?: string;
  traceId?: string;
  result?: {
    documentId?: string;
    parentId?: string | null;
    title?: string | null;
    sortOrder?: number | null;
    workspaceId?: string | null;
    execution?: {
      access_scope?: "private" | "shared" | "public";
      is_template?: boolean;
      created_at?: string | null;
      updated_at?: string | null;
    } | null;
  } | null;
};

export async function POST(request: Request) {
  if (!isConvexEnabled()) {
    return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
  }

  try {
    const { parentId }: { parentId?: string | null } = await request.json();
    const upstreamUrl = new URL("/api/tree/commands", request.url);
    const response = await fetch(upstreamUrl.toString(), {
      method: "POST",
      headers: new Headers({
        "content-type": "application/json",
      }),
      body: JSON.stringify({
        action: "create",
        parentId: typeof parentId === "string" ? parentId.trim() || null : null,
      }),
    });

    const payload = (await response.json().catch(() => null)) as TreeCreateResponse | { error?: string } | null;
    if (!response.ok) {
      return NextResponse.json(
        {
          error:
            payload && typeof payload === "object" && "error" in payload && typeof payload.error === "string"
              ? payload.error
              : "创建页面失败，请稍后再试",
        },
        { status: response.status },
      );
    }

    return NextResponse.json({
      id: payload?.result?.documentId ?? "",
      title: payload?.result?.title ?? "无标题",
      parent_id: payload?.result?.parentId ?? null,
      sort_order: payload?.result?.sortOrder ?? null,
      workspace_id: payload?.result?.workspaceId ?? undefined,
      access_scope: payload?.result?.execution?.access_scope ?? "private",
      is_template: payload?.result?.execution?.is_template ?? false,
      created_at: payload?.result?.execution?.created_at ?? null,
      updated_at:
        payload?.result?.execution?.updated_at ??
        payload?.result?.execution?.created_at ??
        null,
      meta: {
        requestId: payload?.requestId,
        traceId: payload?.traceId,
        commandName: "tree.node.create",
      },
    });
  } catch (error) {
    return NextResponse.json(
      {
        error: error instanceof Error ? error.message : "创建页面失败，请稍后再试",
      },
      { status: 500 },
    );
  }
}

export const runtime = "nodejs";
