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

// WBS 템플릿 Task 저장 (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 parentObjId = String(body.parent_objid || "");
  const taskName = String(body.task_name || "");
  const unitNo = String(body.unit_no || "");
  const taskSeq = String(body.task_seq || "");

  if (!parentObjId) return NextResponse.json({ success: false, message: "PARENT_OBJID 필요" }, { status: 400 });
  if (!taskName) return NextResponse.json({ success: false, message: "UNIT Name을 입력하세요." }, { status: 400 });

  const isNew = !body.objid;
  const objId = isNew ? createObjectId() : String(body.objid);

  try {
    await execute(
      `INSERT INTO pms_wbs_task_standard (objid, parent_objid, task_name, task_seq, user_id, writer, reg_date, unit_no)
       VALUES ($1, $2, $3, $4, $5, $6, now(), $7)
       ON CONFLICT (objid) DO UPDATE SET
         task_name = EXCLUDED.task_name,
         task_seq = EXCLUDED.task_seq,
         user_id = EXCLUDED.user_id,
         unit_no = EXCLUDED.unit_no`,
      [objId, parentObjId, taskName, taskSeq, user.userId, user.userId, unitNo]
    );
    return NextResponse.json({ success: true, objId, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (error) {
    console.error("WBS template task save:", error);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
