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

// WBS 템플릿 하위 Task 목록 (project.getWBSTemplateTaskList 대응)
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { parentObjId } = await request.json();
  if (!parentObjId) return NextResponse.json({ RESULTLIST: [], TOTAL_CNT: 0 });

  const rows = await queryRows(
    `SELECT T.objid::text AS "OBJID",
       T.parent_objid::text AS "PARENT_OBJID",
       T.task_name AS "TASK_NAME",
       T.task_seq AS "TASK_SEQ",
       T.user_id AS "USER_ID",
       (SELECT user_name FROM user_info WHERE user_id = T.user_id LIMIT 1) AS "USER_ID_TITLE",
       T.unit_no AS "UNIT_NO"
     FROM pms_wbs_task_standard T
     WHERE T.parent_objid = $1
     ORDER BY T.unit_no`,
    [parentObjId]
  );

  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
