import { NextResponse } from "next/server";
import { getActiveAccountId } from "@/lib/account-context";
import { authErrorResponse } from "@/lib/auth/api";
import { requireUserAccountScope } from "@/lib/auth/user-scope";
import { prisma } from "@/lib/db";

export async function DELETE(request: Request) {
  try {
    const body = (await request.json()) as { ids?: string[] };
    const ids = [...new Set((body.ids ?? []).filter(Boolean))].slice(0, 100);
    if (ids.length === 0) {
      return NextResponse.json({ error: "請至少選擇一則留言草稿" }, { status: 400 });
    }

    const { where } = await requireUserAccountScope(await getActiveAccountId());
    const drafts = await prisma.outreachDraft.findMany({
      where: {
        id: { in: ids },
        outreachTarget: { scanItem: { scan: { ...where, scanGoal: "placement" } } },
      },
      select: { id: true, status: true, outreachTargetId: true },
    });
    if (drafts.length !== ids.length) {
      return NextResponse.json({ error: "部分草稿不存在或不屬於目前帳號" }, { status: 403 });
    }
    if (drafts.some((draft) => draft.status === "PUBLISHED")) {
      return NextResponse.json({ error: "已發布留言不能只刪除本地紀錄" }, { status: 409 });
    }

    const targetIds = [...new Set(drafts.map((draft) => draft.outreachTargetId))];
    const result = await prisma.$transaction(async (tx) => {
      const deleted = await tx.outreachDraft.deleteMany({ where: { id: { in: ids } } });
      const emptyTargets = await tx.outreachTarget.findMany({
        where: { id: { in: targetIds }, drafts: { none: {} } },
        select: { id: true },
      });
      if (emptyTargets.length > 0) {
        await tx.outreachTarget.deleteMany({
          where: { id: { in: emptyTargets.map((target) => target.id) } },
        });
      }
      return { deleted: deleted.count, removedTargets: emptyTargets.length };
    });

    return NextResponse.json(result);
  } catch (error) {
    const authRes = authErrorResponse(error);
    if (authRes) return authRes;
    const message = error instanceof Error ? error.message : "批次刪除失敗";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
