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

// 부적합 등록/수정 (supplyChainMgmt.saveDeliveryInvalidInfo 대응)
// ARRIVAL_PLAN의 error_qty, error_reason, attribution 업데이트
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  if (!body.objId) {
    return NextResponse.json({ success: false, message: "대상 항목을 선택하세요." });
  }

  try {
    await execute(
      `UPDATE arrival_plan SET
        error_qty = $1,
        error_reason = $2,
        attribution = $3
       WHERE objid = $4`,
      [
        body.error_qty || body.defect_qty || "",
        body.error_reason || body.defect_reason || "",
        body.attribution || "",
        body.objId,
      ]
    );
    return NextResponse.json({ success: true, message: "저장되었습니다." });
  } catch (e) {
    console.error("Defect save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
