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

// 조치내역 팝업용 단건 조회 — sales_part_chg + part_mng_history 헤더 정보 함께
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { objId, partObjId } = await request.json();
  const pid = String(partObjId || "");
  if (!pid) return NextResponse.json({ success: false, message: "partObjId 누락" }, { status: 400 });

  // 부품이력 헤더 (읽기전용 표시)
  const header = await queryOne(
    `SELECT PM.objid::text AS "OBJID",
       PM.eo_no AS "EO_NO",
       PM.part_no AS "PART_NO",
       PM.part_name AS "PART_NAME",
       COALESCE(CM.project_no, CM.contract_no) AS "PROJECT_NO",
       PM.bom_report_objid AS "BOM_REPORT_OBJID",
       PM.qty_child_objid AS "QTY_CHILD_OBJID"
     FROM part_mng_history PM
       LEFT OUTER JOIN project_mgmt CM ON PM.contract_objid = CM.objid
     WHERE PM.objid::text = $1`,
    [pid]
  );

  // 조치내역
  const spc = objId
    ? await queryOne(
        `SELECT objid::text AS "OBJID",
           part_objid AS "PART_OBJID",
           confirm_date AS "CONFIRM_DATE",
           act_cd AS "ACT_CD",
           purchase_order_master_objid AS "PURCHASE_ORDER_MASTER_OBJID",
           note AS "NOTE",
           act_status AS "ACT_STATUS"
         FROM sales_part_chg WHERE objid = $1`,
        [String(objId)]
      )
    : null;

  // 발주서 드롭다운 옵션 (읽기전용으로 고를 수 있게 최신 순)
  const orders = await queryRows(
    `SELECT objid AS "OBJID", purchase_order_no AS "PURCHASE_ORDER_NO"
     FROM purchase_order_master
     WHERE COALESCE(status,'') != 'deleted'
     ORDER BY regdate DESC`
  );

  return NextResponse.json({ success: true, header, spc, orders });
}
