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

// 출고관리 상세 (release_mgmt.objid 기준)
// body: { objId } — release_mgmt.objid
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 RM.objid::text AS "OBJID",
       RM.parent_objid AS "PARENT_OBJID",
       RM.release_date AS "RELEASE_DATE",
       RM.release_car_no AS "RELEASE_CAR_NO",
       RM.writer AS "WRITER",
       RM.task_over_user_id AS "TASK_OVER_USER_ID",
       RM.task_over_date AS "TASK_OVER_DATE",
       RM.task_over_comment AS "TASK_OVER_COMMENT",
       RM.install_complete_date AS "INSTALL_COMPLETE_DATE",
       RM.install_result AS "INSTALL_RESULT",
       RM.product AS "PRODUCT",
       PM.project_no AS "PROJECT_NO",
       PM.project_name AS "PROJECT_NAME",
       COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = PM.customer_objid LIMIT 1), '') AS "CUSTOMER_NAME"
     FROM release_mgmt RM
     LEFT JOIN project_mgmt PM ON PM.objid = RM.parent_objid
     WHERE RM.objid = $1`, [objId]
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });
  return NextResponse.json({ success: true, data: info });
}
