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

// 유닛(UNIT) 목록 (pms_wbs_task) - 특정 프로젝트(contract_objid)의 유닛 드롭다운용
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json().catch(() => ({}));
  const contractObjId = String(body.contract_objid || body.project_name || "");

  const conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;
  if (contractObjId) {
    conditions.push(`T.contract_objid = $${idx++}`);
    params.push(contractObjId);
  }
  const where = conditions.join(" AND ");

  const rows = await queryRows(
    `SELECT T.objid::text AS "OBJID",
       T.unit_no AS "UNIT_NO",
       T.task_name AS "TASK_NAME",
       COALESCE(T.unit_no, '') || '-' || COALESCE(T.task_name, '') AS "UNIT_NAME"
     FROM pms_wbs_task T
     WHERE ${where}
     ORDER BY T.unit_no NULLS LAST, T.task_name
`,
    params,
  );
  return NextResponse.json({ RESULTLIST: rows });
}
