import { NextRequest, NextResponse } from "next/server";
import { execute } from "@/lib/db";
import { getSession } from "@/lib/session";

// PART_BOM_REPORT 삭제 (structureList.jsp fn_delete → /partMng/deleteStructure.do)
// 배포완료/설계변경미배포 상태는 삭제 불가
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const { objIds } = body;
  if (!Array.isArray(objIds) || objIds.length === 0) {
    return NextResponse.json({ success: false, message: "삭제할 항목을 선택하세요." });
  }

  try {
    const placeholders = objIds.map((_: string, i: number) => `$${i + 1}`).join(",");
    await execute(
      `DELETE FROM bom_part_qty WHERE bom_report_objid IN (${placeholders})`,
      objIds,
    );
    await execute(
      `DELETE FROM part_bom_report WHERE objid IN (${placeholders}) AND status NOT IN ('deploy','changeDesign')`,
      objIds,
    );
    return NextResponse.json({ success: true, message: `${objIds.length}건이 삭제되었습니다.` });
  } catch (error) {
    console.error("structure delete:", error);
    return NextResponse.json({ success: false, message: "삭제 중 오류가 발생했습니다." }, { status: 500 });
  }
}
