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

// 발주폼용 부품 검색 (part_mng에서 검색하여 추가)
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[] = ["P.status = 'release'", "P.is_last = 'Y'"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.part_no) {
    conditions.push(`P.part_no LIKE '%' || $${idx++} || '%'`);
    params.push(body.part_no);
  }
  if (body.part_name) {
    conditions.push(`P.part_name LIKE '%' || $${idx++} || '%'`);
    params.push(body.part_name);
  }

  const rows = await queryRows(
    `SELECT P.objid::text AS "PART_OBJID",
       P.part_no AS "PART_NO",
       P.part_name AS "PART_NAME",
       P.spec AS "SPEC",
       P.maker AS "MAKER",
       P.unit AS "UNIT",
       COALESCE(P.qty::text, '0') AS "BOM_QTY"
     FROM part_mng P
     WHERE ${conditions.join(" AND ")}
     ORDER BY P.part_no
`,
    params
  );

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