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

// 원본: /partMng/partMngHisDetailPopUp.do — 부품 변경 이력 조회 (550x250)
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 누락" }, { status: 400 });

  const current = await queryOne(
    `SELECT PM.objid::text AS "OBJID",
       PM.part_no AS "PART_NO",
       PM.part_name AS "PART_NAME",
       PM.revision AS "REVISION",
       PM.eo_no AS "EO_NO",
       PM.eo_date AS "EO_DATE",
       (SELECT code_name FROM comm_code WHERE code_id = PM.change_type LIMIT 1) AS "CHANGE_TYPE_NAME",
       (SELECT code_name FROM comm_code WHERE code_id = PM.change_option LIMIT 1) AS "CHANGE_OPTION_NAME",
       PM.qty AS "QTY",
       PM.qty_temp AS "QTY_TEMP",
       PM.remark AS "REMARK",
       TO_CHAR(PM.reg_date, 'YYYY-MM-DD') AS "REG_DATE",
       COALESCE(
         (SELECT user_name FROM user_info WHERE user_id = PM.writer LIMIT 1),
         (SELECT user_name FROM user_info_history WHERE user_id = PM.writer LIMIT 1),
         PM.writer
       ) AS "WRITER_NAME"
     FROM part_mng_history PM
     WHERE PM.objid::text = $1`,
    [String(objId)]
  );

  if (!current) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });

  // 같은 품번 이력 (같은 project 내)
  const history = await queryRows(
    `SELECT PM.objid::text AS "OBJID",
       PM.revision AS "REVISION",
       PM.eo_no AS "EO_NO",
       PM.eo_date AS "EO_DATE",
       (SELECT code_name FROM comm_code WHERE code_id = PM.change_type LIMIT 1) AS "CHANGE_TYPE_NAME",
       TO_CHAR(PM.reg_date, 'YYYY-MM-DD') AS "REG_DATE",
       COALESCE(
         (SELECT user_name FROM user_info WHERE user_id = PM.writer LIMIT 1),
         (SELECT user_name FROM user_info_history WHERE user_id = PM.writer LIMIT 1),
         PM.writer
       ) AS "WRITER_NAME"
     FROM part_mng_history PM
     WHERE PM.part_no = (SELECT part_no FROM part_mng_history WHERE objid::text = $1)
       AND PM.contract_objid = (SELECT contract_objid FROM part_mng_history WHERE objid::text = $1)
     ORDER BY PM.reg_date DESC
`,
    [String(objId)]
  );

  return NextResponse.json({ success: true, current, history });
}
