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

// 구조등록 우측 PART 검색 (원본: partMng/getPartMngList_ajax.do)
// 최신 Part (is_last='1') 기준으로 품번/품명/규격/MAKER 검색
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json([]);

  const body = await request.json();
  const conditions: string[] = ["P.status = 'release'"];
  const params: unknown[] = [];
  let idx = 1;

  if (String(body.is_last ?? "1") === "1") {
    conditions.push(`P.is_last = '1'`);
  }
  if (body.search_part_no) {
    conditions.push(`UPPER(P.part_no) LIKE UPPER('%' || $${idx++} || '%')`);
    params.push(body.search_part_no);
  }
  if (body.search_part_name) {
    conditions.push(`UPPER(P.part_name) LIKE UPPER('%' || $${idx++} || '%')`);
    params.push(body.search_part_name);
  }
  if (body.search_spec) {
    conditions.push(`UPPER(P.spec) LIKE UPPER('%' || $${idx++} || '%')`);
    params.push(body.search_spec);
  }
  if (body.search_maker) {
    conditions.push(`UPPER(P.maker) LIKE UPPER('%' || $${idx++} || '%')`);
    params.push(body.search_maker);
  }

  const where = conditions.join(" AND ");
  const rows = await queryRows(
    `SELECT P.objid::text AS "OBJID",
       P.part_no AS "PART_NO",
       P.part_name AS "PART_NAME",
       P.spec AS "SPEC",
       P.maker AS "MAKER",
       P.material AS "MATERIAL",
       P.revision AS "REVISION",
       P.part_type AS "PART_TYPE"
     FROM part_mng P
     WHERE ${where}
     ORDER BY P.part_no
`,
    params,
  );
  return NextResponse.json(rows);
}
