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 isNew = !body.objId || body.actionType === "regist";
  const objId = isNew ? createObjectId() : body.objId;

  const client = await pool.connect();
  try {
    await client.query(
      `INSERT INTO product_spec (objid, contract_objid, spec_name, spec_value, unit, remark, writer, reg_date)
       VALUES ($1, $2, $3, $4, $5, $6, $7, now())
       ON CONFLICT (objid) DO UPDATE SET
        spec_name=EXCLUDED.spec_name, spec_value=EXCLUDED.spec_value,
        unit=EXCLUDED.unit, remark=EXCLUDED.remark`,
      [objId, body.contract_objid || body.project_no || "",
       body.spec_name || "", body.spec_value || "",
       body.unit || "", body.remark || "", user.userId]
    );
    return NextResponse.json({ success: true, objId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("Spec save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally { client.release(); }
}
