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

// PartMngController / partmgmt.getPartMgntList 대응
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 { part_no, part_name, part_type, page = 1 } = body;
  const countPerPage = 20;

  const conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  if (part_no) { conditions.push(`P.PART_NO LIKE '%' || $${idx++} || '%'`); params.push(part_no); }
  if (part_name) { conditions.push(`P.PART_NAME LIKE '%' || $${idx++} || '%'`); params.push(part_name); }
  if (part_type) { conditions.push(`P.PART_TYPE = $${idx++}`); params.push(part_type); }

  const where = conditions.join(" AND ");
  const offset = (Number(page) - 1) * countPerPage;

  const list = await queryRows(
    `SELECT P.OBJID, P.PART_NO, P.PART_NAME,
            COALESCE((SELECT CODE_NAME FROM COMM_CODE WHERE PARENT_CODE_ID = '0000062' AND CODE_ID = P.PART_TYPE LIMIT 1), '') AS PART_TYPE_NAME,
            P.SPEC, P.MATERIAL,
            COALESCE((SELECT CODE_NAME FROM COMM_CODE WHERE PARENT_CODE_ID = '0005126' AND CODE_ID = P.MATERIAL LIMIT 1), '') AS MATERIAL_NAME,
            COALESCE((SELECT CODE_NAME FROM COMM_CODE WHERE PARENT_CODE_ID = '0000059' AND CODE_ID = P.UNIT LIMIT 1), '') AS UNIT_NAME,
            P.WEIGHT, P.MAKER,
            (SELECT USER_NAME FROM USER_INFO WHERE USER_ID = P.WRITER LIMIT 1) AS WRITER_NAME,
            TO_CHAR(P.REGDATE::date, 'YYYY-MM-DD') AS REGDATE,
            COALESCE((SELECT COUNT(*) FROM ATTACH_FILE_INFO WHERE TARGET_OBJID = P.OBJID AND DOC_TYPE = 'PART_2D'), 0) AS DRAWING_2D_CNT,
            COALESCE((SELECT COUNT(*) FROM ATTACH_FILE_INFO WHERE TARGET_OBJID = P.OBJID AND DOC_TYPE = 'PART_3D'), 0) AS DRAWING_3D_CNT
     FROM PART_MGMT P
     WHERE ${where}
     ORDER BY P.REGDATE DESC
     LIMIT $${idx++} OFFSET $${idx++}`,
    [...params, countPerPage, offset]
  );

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