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

// WBS 템플릿 저장 (project.saveWBSTemplateTaskInfo 대응)
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 pms_wbs_template (objid, title, product_objid, customer_product, writer, reg_date)
       VALUES ($1, $2, $3, $4, $5, now())
       ON CONFLICT (objid) DO UPDATE SET
         title = EXCLUDED.title,
         product_objid = EXCLUDED.product_objid,
         customer_product = EXCLUDED.customer_product`,
      [objId, body.title || "", body.product_objid || "", body.customer_product || "", user.userId]
    );
    return NextResponse.json({ success: true, objId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (error) {
    console.error("WBS template save:", error);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
