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

// 출고관리 단건 조회 — project_objid(접수 프로젝트)로 조회
// release_mgmt는 없을 수 있음(신규 등록 케이스), 그 경우 프로젝트/계약 정보만 반환
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 projectObjId = String(body.projectObjId || body.objId || "");
  if (!projectObjId) {
    return NextResponse.json({ success: false, message: "projectObjId 누락" }, { status: 400 });
  }

  const info = await queryOne(
    `SELECT
      PM.objid::text AS "PROJECT_OBJID",
      PM.contract_objid::text AS "CONTRACT_OBJID",
      PM.project_no AS "PROJECT_NO",
      PM.project_name AS "PROJECT_NAME",
      PM.product AS "PRODUCT",
      (SELECT code_name FROM comm_code WHERE code_id = PM.product LIMIT 1) AS "PRODUCT_NAME",
      PM.mechanical_type AS "MECHANICAL_TYPE",
      CM.customer_objid AS "CUSTOMER_OBJID",
      (SELECT supply_name FROM supply_mng WHERE objid::text = CM.customer_objid LIMIT 1) AS "CUSTOMER_NAME",
      (SELECT code_name FROM comm_code WHERE code_id = CM.category_cd LIMIT 1) AS "CATEGORY_NAME",
      CM.contract_del_date AS "CONTRACT_DEL_DATE",
      CM.req_del_date AS "REQ_DEL_DATE",
      CM.location AS "LOCATION",
      CM.setup AS "SETUP",
      CM.facility_type AS "FACILITY_TYPE",
      RM.objid AS "RELEASE_OBJID",
      RM.release_car_no AS "RELEASE_CAR_NO",
      RM.release_date AS "RELEASE_DATE",
      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"
    FROM project_mgmt PM
    JOIN contract_mgmt CM ON CM.objid = PM.contract_objid
    LEFT JOIN release_mgmt RM
      ON RM.parent_objid = PM.contract_objid AND COALESCE(RM.product,'') = COALESCE(PM.product,'')
    WHERE PM.objid::text = $1`,
    [projectObjId]
  );

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