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

// 계약 상세 조회 (contracMgmtFormPopup.do 대응)
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 { objId } = body;
  if (!objId) return NextResponse.json({ success: false, message: "objId required" });

  const info = await queryOne(
    `SELECT CM.objid::text AS "OBJID", CM.contract_no AS "CONTRACT_NO",
      CM.category_cd AS "CATEGORY_CD", CM.area_cd AS "AREA_CD",
      CM.customer_objid AS "CUSTOMER_OBJID", CM.product AS "PRODUCT",
      CM.mechanical_type AS "MECHANICAL_TYPE",
      CM.customer_project_name AS "CUSTOMER_PROJECT_NAME",
      CM.due_date AS "DUE_DATE", CM.location AS "LOCATION", CM.setup AS "SETUP",
      CM.facility AS "FACILITY", CM.facility_qty AS "FACILITY_QTY",
      CM.facility_type AS "FACILITY_TYPE", CM.facility_depth AS "FACILITY_DEPTH",
      CM.contract_result AS "CONTRACT_RESULT",
      CM.contract_date AS "CONTRACT_DATE", CM.po_no AS "PO_NO",
      CM.pm_user_id AS "PM_USER_ID",
      CM.contract_currency AS "CONTRACT_CURRENCY",
      CM.contract_price_currency AS "CONTRACT_PRICE_CURRENCY",
      CM.contract_price AS "CONTRACT_PRICE",
      CM.project_name AS "PROJECT_NAME",
      CM.contract_del_date AS "CONTRACT_DEL_DATE",
      CM.req_del_date AS "REQ_DEL_DATE",
      CM.contract_company AS "CONTRACT_COMPANY",
      CM.manufacture_plant AS "MANUFACTURE_PLANT",
      CM.target_project_no AS "TARGET_PROJECT_NO",
      CM.target_project_no_direct AS "TARGET_PROJECT_NO_DIRECT",
      CM.customer_production_no AS "CUSTOMER_PRODUCTION_NO",
      CM.overhaul_order AS "OVERHAUL_ORDER",
      CM.writer AS "WRITER",
      COALESCE((SELECT user_name FROM user_info WHERE user_id = CM.writer LIMIT 1), '') AS "WRITER_NAME",
      TO_CHAR(CM.regdate, 'YYYY-MM-DD') AS "REGDATE"
     FROM contract_mgmt CM
     WHERE CM.objid = $1`,
    [objId]
  );

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