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

// 예측수량 일괄 저장 (기존 행 delete 후 re-insert)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { parentObjId, rows } = await request.json();
  if (!parentObjId) return NextResponse.json({ success: false, message: "parentObjId 누락" }, { status: 400 });

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query(`DELETE FROM sales_long_delivery_predict WHERE parent_objid = $1`, [String(parentObjId)]);

    const list = Array.isArray(rows) ? rows : [];
    for (const r of list) {
      const qty = String(r.QTY ?? r.qty ?? "");
      if (!qty) continue;
      await client.query(
        `INSERT INTO sales_long_delivery_predict (
           objid, parent_objid, month, use_place, qty, note, contract_objid
         ) VALUES ($1, $2, $3, $4, $5, $6, $7)`,
        [
          String(r.OBJID || r.objid || "") || createObjectId(),
          String(parentObjId),
          String(r.MONTH ?? r.month ?? ""),
          String(r.USE_PLACE ?? r.use_place ?? ""),
          qty,
          String(r.NOTE ?? r.note ?? ""),
          String(r.CONTRACT_OBJID ?? r.contract_objid ?? ""),
        ]
      );
    }

    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: "저장되었습니다." });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("stock predict-save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
