import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { deleteDraftImages, parseDraftImagePaths } from "@/lib/drafts/images";
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;
      angle?: string;
      rationale?: string;
    };

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

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

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

export async function DELETE(
  _request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;

    const draft = await prisma.draft.findUnique({ where: { id } });
    if (!draft) {
      return NextResponse.json({ error: "找不到草稿" }, { status: 404 });
    }
    await deleteDraftImages(parseDraftImagePaths(draft));

    await prisma.draft.update({
      where: { id },
      data: { status: "REJECTED", imagePath: null, imagePaths: null },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    return apiRouteErrorResponse(error, "drafts/delete");
  }
}