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

// 원본: mergeSalesLongDelivery
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 isNew = !body.objId;
  const objId = isNew ? createObjectId() : String(body.objId);

  const client = await pool.connect();
  try {
    await client.query(
      `INSERT INTO sales_long_delivery (
         objid, ld_part_name, spec, form_no, maker, material_code,
         supply_objid, regdate, writer, location, price
       ) VALUES ($1, $2, $3, $4, $5, $6, $7, now(), $8, $9, $10)
       ON CONFLICT (objid) DO UPDATE SET
         ld_part_name = EXCLUDED.ld_part_name,
         spec = EXCLUDED.spec,
         form_no = EXCLUDED.form_no,
         maker = EXCLUDED.maker,
         material_code = EXCLUDED.material_code,
         supply_objid = EXCLUDED.supply_objid,
         regdate = now(),
         writer = EXCLUDED.writer,
         location = EXCLUDED.location,
         price = EXCLUDED.price`,
      [
        objId,
        String(body.ld_part_name || ""),
        String(body.spec || ""),
        String(body.form_no || ""),
        String(body.maker || ""),
        String(body.material_code || ""),
        String(body.supply_objid || ""),
        user.userId,
        String(body.location || ""),
        String(body.price || "0"),
      ]
    );
    return NextResponse.json({ success: true, objId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("stock save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
