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

// 입고결과등록 팝업 상세 조회
// 원본:
//   - purchaseOrderService.getPurchaseOrderMasterInfo → info
//   - purchaseOrder.getPurchaseOrderDeliveryTargetPartList → partList (발주파트+기입고/미입고)
//   - supplyChainMgmt.arrivalResultList → arrivalList (차수별 arrival_plan)
//   - purchaseOrder.selectPurchaseOrderMasterList → multiMasterList (동시발주 슬레이브)
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가 필요합니다." });

  // 1. 발주 마스터 정보 (readonly 표시용)
  const info = await queryOne(
    `SELECT POM.objid::text AS "OBJID",
       POM.purchase_order_no AS "PURCHASE_ORDER_NO",
       POM.purchase_order_no_org AS "PURCHASE_ORDER_NO_ORG",
       POM.title AS "TITLE",
       POM.delivery_date AS "DELIVERY_DATE",
       TO_CHAR(POM.regdate, 'YYYY-MM-DD') AS "REGDATE",
       POM.type AS "TYPE",
       (SELECT code_name FROM comm_code WHERE code_id = POM.type LIMIT 1) AS "TYPE_NAME",
       POM.order_type_cd AS "ORDER_TYPE_CD",
       (SELECT code_name FROM comm_code WHERE code_id = POM.order_type_cd LIMIT 1) AS "ORDER_TYPE_CD_NAME",
       POM.delivery_place AS "DELIVERY_PLACE",
       (SELECT code_name FROM comm_code WHERE code_id = POM.delivery_place LIMIT 1) AS "DELIVERY_PLACE_NAME",
       POM.inspect_method AS "INSPECT_METHOD",
       (SELECT code_name FROM comm_code WHERE code_id = POM.inspect_method LIMIT 1) AS "INSPECT_METHOD_NAME",
       POM.payment_terms AS "PAYMENT_TERMS",
       (SELECT code_name FROM comm_code WHERE code_id = POM.payment_terms LIMIT 1) AS "PAYMENT_TERMS_NAME",
       POM.total_price_txt AS "TOTAL_PRICE_TXT",
       POM.remark AS "REMARK",
       POM.status AS "STATUS",
       COALESCE(POM.multi_yn, '') AS "MULTI_YN",
       COALESCE(POM.multi_master_yn, '') AS "MULTI_MASTER_YN",
       POM.multi_master_objid AS "MULTI_MASTER_OBJID",
       POM.bom_report_objid AS "BOM_REPORT_OBJID",
       POM.contract_mgmt_objid AS "CONTRACT_MGMT_OBJID",
       COALESCE(CM.project_no, CM.contract_no) AS "PROJECT_NO",
       CM.customer_project_name AS "CUSTOMER_PROJECT_NAME",
       POM.unit_code AS "UNIT_CODE",
       (SELECT COALESCE(O.unit_no,'') || '-' || COALESCE(O.task_name,'') FROM pms_wbs_task O WHERE O.objid = POM.unit_code LIMIT 1) AS "UNIT_NAME",
       POM.partner_objid AS "PARTNER_OBJID",
       (SELECT supply_name FROM admin_supply_mng WHERE objid::text = POM.partner_objid LIMIT 1) AS "PARTNER_NAME",
       (SELECT bus_reg_no FROM admin_supply_mng WHERE objid::text = POM.partner_objid LIMIT 1) AS "SUPPLY_BUS_NO",
       (SELECT supply_address FROM admin_supply_mng WHERE objid::text = POM.partner_objid LIMIT 1) AS "SUPPLY_ADDR",
       POM.supply_user_name AS "SUPPLY_USER_NAME",
       POM.supply_user_hp AS "SUPPLY_USER_HP",
       POM.supply_user_tel AS "SUPPLY_USER_TEL",
       POM.supply_user_fax AS "SUPPLY_USER_FAX",
       POM.supply_user_email AS "SUPPLY_USER_EMAIL",
       POM.sales_mng_user_id AS "SALES_MNG_USER_ID",
       (SELECT user_name FROM user_info WHERE user_id = POM.sales_mng_user_id LIMIT 1) AS "SALES_MNG_USER",
       (SELECT cell_phone FROM user_info WHERE user_id = POM.sales_mng_user_id LIMIT 1) AS "SALES_MNG_USER_CELL_PHONE"
     FROM purchase_order_master POM
     LEFT JOIN project_mgmt CM ON POM.contract_mgmt_objid = CM.objid
     WHERE POM.objid::text = $1`,
    [String(objId)],
  );
  if (!info) {
    return NextResponse.json({ success: false, message: "발주서를 찾을 수 없습니다." });
  }

  // 2. 파트 목록 + 기입고/미입고 수량
  const partList = await queryRows(
    `SELECT
       POP.objid::text AS "ORDER_PART_OBJID",
       POP.part_objid AS "PART_OBJID",
       POP.ld_part_objid AS "LD_PART_OBJID",
       CASE WHEN POM.type IN ('0001070','0001069') THEN COALESCE(PM.part_no, POP.part_no) ELSE POP.part_no END AS "PART_NO",
       POP.part_name AS "PART_NAME",
       COALESCE(PM.material, '') AS "MATERIAL",
       POP.spec AS "SPEC",
       POP.maker AS "MAKER",
       (SELECT code_name FROM comm_code WHERE code_id = POP.unit LIMIT 1) AS "UNIT_TITLE",
       POP.order_qty AS "ORDER_QTY",
       POP.real_order_qty AS "REAL_ORDER_QTY",
       POM.delivery_date AS "POM_DELIVERY_DATE",
       COALESCE(AP.total_delivery_qty, '0') AS "TOTAL_DELIVERY_QTY",
       (COALESCE(POP.real_order_qty,'0')::numeric - COALESCE(AP.total_delivery_qty, '0')::numeric) AS "NON_ARRIVAL_QTY"
     FROM purchase_order_master POM
     INNER JOIN purchase_order_part POP ON POM.objid::text = POP.purchase_order_master_objid
     LEFT JOIN part_mng PM ON POP.part_objid = PM.objid::text
     LEFT JOIN (
       SELECT order_part_objid,
              SUM(COALESCE(receipt_qty,'0')::numeric)::text AS total_delivery_qty
         FROM arrival_plan
        WHERE parent_objid = $1
        GROUP BY order_part_objid
     ) AP ON AP.order_part_objid = POP.objid::text
     WHERE POM.objid::text = $1
     ORDER BY PM.part_no NULLS LAST, POP.regdate DESC`,
    [String(objId)],
  );

  // 3. 기존 차수별 입고계획 (arrival_plan)
  const arrivalList = await queryRows(
    `SELECT
       AP.objid::text AS "OBJID",
       AP.part_objid AS "PART_OBJID",
       AP.order_part_objid AS "ORDER_PART_OBJID",
       AP.arrival_qty AS "ARRIVAL_QTY",
       AP.arrival_plan_date AS "ARRIVAL_PLAN_DATE",
       AP.group_seq AS "GROUP_SEQ",
       AP.seq AS "SEQ",
       AP.receipt_qty AS "RECEIPT_QTY",
       AP.receipt_date AS "RECEIPT_DATE",
       AP.location AS "LOCATION",
       AP.sub_location AS "SUB_LOCATION",
       AP.error_qty AS "ERROR_QTY",
       AP.error_reason AS "ERROR_REASON",
       AP.attribution AS "ATTRIBUTION",
       AP.inventory_status AS "INVENTORY_STATUS",
       IM.objid::text AS "INVOICE_OBJID"
     FROM arrival_plan AP
     LEFT JOIN invoice_mgmt IM ON IM.parent_objid::text = AP.parent_objid AND IM.group_seq = AP.group_seq
     WHERE AP.parent_objid = $1
     ORDER BY NULLIF(AP.seq,'')::numeric NULLS LAST, AP.objid`,
    [String(objId)],
  );

  // 4. 동시발주 슬레이브 리스트 (현재 건이 마스터인 경우)
  let multiMasterList: Record<string, unknown>[] = [];
  if (String(info.MULTI_MASTER_YN) === "Y") {
    multiMasterList = await queryRows(
      `SELECT POM.objid::text AS "OBJID",
              POM.contract_mgmt_objid::text AS "CONTRACT_MGMT_OBJID",
              POM.unit_code AS "UNIT_CODE",
              (SELECT project_no FROM project_mgmt CNT WHERE CNT.objid = POM.contract_mgmt_objid LIMIT 1) AS "CONTRACT_NO",
              POM.delivery_date AS "DELIVERY_PLAN_DATE",
              (SELECT SUM(COALESCE(real_order_qty,'0')::numeric)::text FROM purchase_order_part WHERE purchase_order_master_objid = POM.objid::text) AS "DELIVERY_PLAN_QTY"
         FROM purchase_order_master POM
        WHERE POM.multi_master_objid = $1
        ORDER BY "CONTRACT_NO" DESC`,
      [String(objId)],
    );
  }

  return NextResponse.json({
    success: true,
    info,
    partList,
    arrivalList,
    multiMasterList,
  });
}
