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

// PART 등록 페이지 전용 조회 (part-register에서 호출)
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'"];
  const params: unknown[] = [];
  let idx = 1;
  if (body.SEARCH_PART_NO) { conditions.push(`P.part_no LIKE '%' || $${idx++} || '%'`); params.push(body.SEARCH_PART_NO); }
  if (body.SEARCH_PART_NAME) { conditions.push(`P.part_name LIKE '%' || $${idx++} || '%'`); params.push(body.SEARCH_PART_NAME); }

  const rows = await queryRows(
    `SELECT P.objid::text AS "OBJID", P.part_no AS "PART_NO", P.part_name AS "PART_NAME",
       P.qty AS "BOM_QTY", P.material AS "MATERIAL", P.spec AS "SPEC",
       P.post_processing AS "POST_PROCESSING", P.maker AS "MAKER", P.revision AS "REVISION",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = P.part_type LIMIT 1), '') AS "PART_TYPE_TITLE",
       P.remark AS "REMARK",
       COALESCE((SELECT COUNT(*) FROM attach_file_info WHERE target_objid = P.objid::text AND doc_type = '3D_CAD'), 0) AS "CU01_CNT",
       COALESCE((SELECT COUNT(*) FROM attach_file_info WHERE target_objid = P.objid::text AND doc_type = '2D_DRAWING_CAD'), 0) AS "CU02_CNT",
       COALESCE((SELECT COUNT(*) FROM attach_file_info WHERE target_objid = P.objid::text AND doc_type = '2D_PDF_CAD'), 0) AS "CU03_CNT"
     FROM part_mng P
     WHERE ${conditions.join(" AND ")}
     ORDER BY P.part_no, P.revision DESC
`,
    params
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
