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

// BOM 배포 - 배포사유 입력 후 (changeDesignNotePopUp.jsp → saveChangeDesignInfo + deployStructure)
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 note = String(body.NOTE || "");
  const objIdsRaw = String(body.OBJID || "");
  const objIds = objIdsRaw.split(",").map((s) => s.trim()).filter(Boolean);
  if (objIds.length === 0) {
    return NextResponse.json({ success: false, message: "배포할 항목이 없습니다." });
  }

  try {
    const placeholders = objIds.map((_, i) => `$${i + 2}`).join(",");
    // saveChangeDesignInfo: NOTE 업데이트
    await execute(
      `UPDATE part_bom_report SET note = $1 WHERE objid IN (${placeholders})`,
      [note, ...objIds],
    );
    // deployStructure: status = deploy, deploy_date = now
    await execute(
      `UPDATE part_bom_report SET status = 'deploy', deploy_date = TO_CHAR(NOW(), 'YYYY-MM-DD')
       WHERE objid IN (${placeholders.replace(/\$(\d+)/g, (_, n) => `$${Number(n) - 1}`)})`,
      objIds,
    );
    return NextResponse.json({ success: true, message: "배포되었습니다." });
  } catch (error) {
    console.error("bom deploy:", error);
    return NextResponse.json({ success: false, message: "배포 중 오류가 발생했습니다." }, { status: 500 });
  }
}
