import { NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { getActiveAccountId } from "@/lib/account-context";
import { apiRouteErrorResponse } from "@/lib/auth/api";
import { requireUserAccountScope } from "@/lib/auth/user-scope";
import { deleteDraftImages, parseDraftImagePaths } from "@/lib/drafts/images";

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const statusParam = searchParams.get("status");

    const statuses = statusParam
      ? statusParam.split(",").map((s) => s.trim())
      : undefined;
    const accountId = await getActiveAccountId();
    const { where: accountWhere } = await requireUserAccountScope(accountId);

    const drafts = await prisma.draft.findMany({
      where: {
        ...accountWhere,
        ...(statuses
          ? { status: { in: statuses } }
          : { status: { notIn: ["PUBLISHED", "REJECTED"] } }),
      },
      orderBy: { createdAt: "desc" },
    });

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

export async function DELETE(request: Request) {
  try {
    const body = (await request.json()) as { ids?: unknown };
    const ids = Array.isArray(body.ids)
      ? body.ids.filter((id): id is string => typeof id === "string" && id.length > 0)
      : [];

    if (ids.length === 0) {
      return NextResponse.json({ error: "請提供要刪除的草稿 ID" }, { status: 400 });
    }

    const accountId = await getActiveAccountId();
    const { where: accountWhere } = await requireUserAccountScope(accountId);

    const drafts = await prisma.draft.findMany({
      where: {
        id: { in: ids },
        ...accountWhere,
        status: { not: "REJECTED" },
      },
    });

    for (const draft of drafts) {
      await deleteDraftImages(parseDraftImagePaths(draft));
      await prisma.draft.update({
        where: { id: draft.id },
        data: { status: "REJECTED", imagePath: null, imagePaths: null },
      });
    }

    return NextResponse.json({ deleted: drafts.length });
  } catch (error) {
    return apiRouteErrorResponse(error, "drafts");
  }
}