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

// 프로젝트 목록 (project_mgmt) - 드롭다운용
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 conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.customer_cd) {
    conditions.push(`P.customer_objid::text = $${idx++}`);
    params.push(body.customer_cd);
  }

  const where = conditions.join(" AND ");
  const rows = await queryRows(
    `SELECT P.objid::text AS "OBJID",
       P.project_no AS "PROJECT_NO",
       P.customer_project_name AS "CUSTOMER_PROJECT_NAME",
       COALESCE(P.project_no, '') || ' - ' || COALESCE(P.customer_project_name, '') AS "LABEL"
     FROM project_mgmt P
     WHERE ${where}
     ORDER BY P.regdate DESC
`,
    params,
  );
  return NextResponse.json({ RESULTLIST: rows });
}
