import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { THREADS_MAX_CHARS } from "@/lib/utils";
import { apiRouteErrorResponse } from "@/lib/auth/api";

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const body = (await request.json().catch(() => ({}))) as { text?: string; status?: string };

    if (body.text && body.text.length > THREADS_MAX_CHARS) {
      return NextResponse.json({ error: `超過 ${THREADS_MAX_CHARS} 字上限` }, { status: 400 });
    }

    const draft = await prisma.replyDraft.update({
      where: { id },
      data: {
        ...(body.text !== undefined && { text: body.text }),
        ...(body.status !== undefined && { status: body.status }),
      },
    });

    return NextResponse.json({ draft });
  } catch (error) {
    return apiRouteErrorResponse(error, "reply-drafts/patch");
  }
}
