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

// 프로젝트관리 > 제품구분_UNIT관리 (pms_wbs_template)
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 conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  // 원본 JSP: 제품구분(product)만 검색 파라미터로 사용
  if (body.product) {
    conditions.push(`T.product_objid = $${idx++}`);
    params.push(body.product);
  }

  const where = conditions.join(" AND ");

  const rows = await queryRows(
    `SELECT T.objid::text AS "OBJID",
      T.product_objid AS "PRODUCT_OBJID",
      COALESCE((SELECT code_name FROM comm_code WHERE code_id = T.product_objid LIMIT 1), '') AS "PRODUCT_NAME",
      T.title AS "TITLE",
      T.customer_product AS "CUSTOMER_PRODUCT",
      T.writer AS "WRITER",
      COALESCE((SELECT COALESCE(dept_name, '') || user_name FROM user_info WHERE user_id = T.writer LIMIT 1), T.writer) AS "WRITER_TITLE",
      TO_CHAR(T.reg_date, 'YYYY-MM-DD') AS "REG_DATE_TITLE",
      COALESCE((SELECT COUNT(*) FROM pms_wbs_task_standard WHERE parent_objid = T.objid), 0) AS "WBS_TASK_CNT"
     FROM pms_wbs_template T
     WHERE ${where}
     ORDER BY T.product_objid, T.title`,
    params
  );

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