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

// 품목 상세 (원본: partMng/partMngHisDetailPopUp.do → partMngService.getPartMngInfo)
// 설계변경 리스트에서 넘긴 OBJID 로 PART_MNG 를 조회 (part_mng_history 아님)
// + 첨부파일(3D_CAD / 2D_DRAWING_CAD / 2D_PDF_CAD) 목록 동봉
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });
  const { objId } = await request.json();
  if (!objId) return NextResponse.json({ success: false, message: "objId required" });

  const info = await queryOne(
    `SELECT P.objid::text AS "OBJID",
       P.part_no AS "PART_NO", P.part_name AS "PART_NAME",
       P.spec AS "SPEC", P.material AS "MATERIAL", P.weight AS "WEIGHT",
       P.unit AS "UNIT", P.qty AS "QTY",
       P.part_type AS "PART_TYPE",
       (SELECT code_name FROM comm_code WHERE code_id = P.part_type) AS "PART_TYPE_TITLE",
       P.maker AS "MAKER", P.post_processing AS "POST_PROCESSING",
       P.remark AS "REMARK",
       P.revision AS "REVISION", P.status AS "STATUS", P.is_last AS "IS_LAST",
       P.change_type AS "CHANGE_TYPE",
       (SELECT code_name FROM comm_code WHERE code_id = P.change_type) AS "CHANGE_TYPE_NAME",
       P.change_option AS "CHANGE_OPTION",
       (SELECT code_name FROM comm_code WHERE code_id = P.change_option) AS "CHANGE_OPTION_NAME",
       P.thickness AS "THICKNESS", P.width AS "WIDTH", P.height AS "HEIGHT",
       P.out_diameter AS "OUT_DIAMETER", P.in_diameter AS "IN_DIAMETER", P.length AS "LENGTH",
       P.major_category AS "MAJOR_CATEGORY", P.sub_category AS "SUB_CATEGORY",
       P.eo_no AS "EO_NO", P.eo_date AS "EO_DATE",
       P.writer AS "WRITER",
       (SELECT user_name FROM user_info WHERE user_id = P.writer) AS "WRITER_NAME",
       TO_CHAR(P.reg_date, 'YYYY-MM-DD') AS "REG_DATE"
     FROM part_mng P WHERE P.objid = $1`,
    [objId],
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });

  const files = await queryRows(
    `SELECT objid::text AS "OBJID", real_file_name AS "REAL_FILE_NAME",
            doc_type AS "DOC_TYPE"
       FROM attach_file_info
      WHERE target_objid = $1
        AND doc_type IN ('3D_CAD', '2D_DRAWING_CAD', '2D_PDF_CAD')
      ORDER BY regdate DESC`,
    [objId],
  );

  return NextResponse.json({ success: true, data: info, files });
}
