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

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 client = await pool.connect();
  // arrival_plan의 error_qty/error_reason/attribution 업데이트
  try {
    if (body.objId) {
      await client.query(
        `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("SCM defect save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." });
  } finally { client.release(); }
}
