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

// 원본: purchaseOrder.xml#getPurchaseOrderMasterInfo + getPurchaseOrderTargetPartList
// 발주서 상세 — master 헤더 + parts 목록 (읽기전용 팝업용)
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 POM.objid::text AS "OBJID",
       POM.purchase_order_no AS "PURCHASE_ORDER_NO",
       POM.title AS "TITLE",
       POM.contract_mgmt_objid::text AS "CONTRACT_MGMT_OBJID",
       (SELECT project_no FROM project_mgmt CM WHERE CM.objid = POM.contract_mgmt_objid) AS "PROJECT_NO",
       (SELECT customer_project_name FROM project_mgmt CM WHERE CM.objid = POM.contract_mgmt_objid) AS "CUSTOMER_PROJECT_NAME",
       (SELECT contract_no FROM project_mgmt CM WHERE CM.objid = POM.contract_mgmt_objid) AS "CONTRACT_NO",
       (SELECT supply_name FROM supply_mng SM WHERE SM.objid::text =
          (SELECT customer_objid FROM project_mgmt CM WHERE CM.objid = POM.contract_mgmt_objid)::text LIMIT 1) AS "CUSTOMER_NAME",
       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.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.delivery_date AS "DELIVERY_DATE",
       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.effective_date AS "EFFECTIVE_DATE",
       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.inspect_method AS "INSPECT_METHOD",
       (SELECT code_name FROM comm_code WHERE code_id = POM.inspect_method LIMIT 1) AS "INSPECT_METHOD_NAME",
       POM.vat_method AS "VAT_METHOD",
       (SELECT code_name FROM comm_code WHERE code_id = POM.vat_method LIMIT 1) AS "VAT_METHOD_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",
       POM.po_client_id AS "PO_CLIENT_ID",
       SM_PC.supply_name AS "PO_CLIENT_NAME",
       SM_PC.bus_reg_no AS "PO_CLIENT_BUS_NO",
       SM_PC.charge_user_name AS "PO_CLIENT_CHARGER",
       SM_PC.supply_address AS "PO_CLIENT_ADDR",
       SM_PC.supply_tel_no AS "PO_CLIENT_TEL",
       SM_PC.supply_fax_no AS "PO_CLIENT_FAX",
       SM_PC.office_no AS "PO_CLIENT_HP",
       SM_PC.email AS "PO_CLIENT_EMAIL",
       POM.my_company_objid AS "MY_COMPANY_OBJID",
       POM.supply_bus_no AS "SUPPLY_BUS_NO",
       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.supply_addr AS "SUPPLY_ADDR",
       SM_P.bus_reg_no AS "PARTNER_BUS_NO",
       SM_P.charge_user_name AS "PARTNER_CHARGER",
       SM_P.supply_address AS "PARTNER_ADDR",
       SM_P.supply_tel_no AS "PARTNER_TEL",
       SM_P.supply_fax_no AS "PARTNER_FAX",
       SM_P.office_no AS "PARTNER_HP",
       SM_P.email AS "PARTNER_EMAIL",
       COALESCE(POM.total_price,'0') AS "TOTAL_PRICE",
       COALESCE(POM.total_price_all,'0') AS "TOTAL_PRICE_ALL",
       COALESCE(POM.discount_price,'0') AS "DISCOUNT_PRICE",
       COALESCE(POM.discount_price_all,'0') AS "DISCOUNT_PRICE_ALL",
       COALESCE(POM.total_supply_price,'0') AS "TOTAL_SUPPLY_PRICE",
       COALESCE(POM.total_supply_unit_price,'0') AS "TOTAL_SUPPLY_UNIT_PRICE",
       COALESCE(POM.total_real_supply_price,'0') AS "TOTAL_REAL_SUPPLY_PRICE",
       POM.nego_rate AS "NEGO_RATE",
       POM.total_price_txt AS "TOTAL_PRICE_TXT",
       POM.total_price_txt_all AS "TOTAL_PRICE_TXT_ALL",
       POM.remark AS "REMARK",
       POM.writer AS "WRITER",
       (SELECT user_name FROM user_info WHERE user_id = POM.writer LIMIT 1) AS "WRITER_NAME",
       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_NAME",
       POM.regdate AS "REGDATE",
       TO_CHAR(POM.regdate, 'YYYY-MM-DD') AS "REGDATE_TITLE",
       POM.status AS "STATUS",
       CASE POM.status
         WHEN 'create' THEN '등록'
         WHEN 'approvalRequest' THEN '결재중'
         WHEN 'approvalComplete' THEN '결재완료'
         WHEN 'reject' THEN '반려'
         WHEN 'cancel' THEN '취소'
         ELSE ''
       END AS "STATUS_TITLE",
       COALESCE(POM.multi_yn,'') AS "MULTI_YN",
       COALESCE(POM.multi_master_yn,'') AS "MULTI_MASTER_YN",
       POM.multi_master_objid AS "MULTI_MASTER_OBJID",
       (SELECT ARRAY_TO_STRING(ARRAY_AGG(S.objid), ',') FROM purchase_order_master S
          WHERE POM.objid = S.multi_master_objid) AS "MULTI_OBJIDS",
       POM.sales_request_objid AS "SALES_REQUEST_OBJID",
       POM.bom_report_objid AS "BOM_REPORT_OBJID",
       POM.purchase_order_no_org AS "PURCHASE_ORDER_NO_ORG",
       POM.sales_status AS "SALES_STATUS",
       POM.reception_status AS "RECEPTION_STATUS"
     FROM purchase_order_master POM
       LEFT OUTER JOIN admin_supply_mng SM_PC ON POM.po_client_id::text = SM_PC.objid::text
       LEFT OUTER JOIN admin_supply_mng SM_P ON POM.partner_objid::text = SM_P.objid::text
     WHERE POM.objid::text = $1`,
    [String(objId)],
  );
  if (!info) return NextResponse.json({ success: false, message: "데이터를 찾을 수 없습니다." });

  const parts = await queryRows(
    `SELECT POP.objid::text AS "OBJID",
       POP.purchase_order_master_objid::text AS "PURCHASE_ORDER_MASTER_OBJID",
       POP.part_objid AS "PART_OBJID",
       CASE WHEN POM.type IN ('0001070','0001069') THEN PM.part_no ELSE POP.part_no END AS "PART_NO",
       COALESCE(POP.part_name, PM.part_name) AS "PART_NAME",
       COALESCE(POP.spec, PM.spec) AS "SPEC",
       COALESCE(POP.maker, PM.maker) AS "MAKER",
       PM.material AS "MATERIAL",
       PM.revision AS "REVISION",
       POP.unit AS "UNIT",
       (SELECT code_name FROM comm_code WHERE code_id = POP.unit LIMIT 1) AS "UNIT_NAME",
       COALESCE(POP.order_qty,'0') AS "ORDER_QTY",
       COALESCE(POP.partner_price,'0') AS "PARTNER_PRICE",
       COALESCE(POP.price1,'0') AS "PRICE1",
       COALESCE(POP.price2,'0') AS "PRICE2",
       COALESCE(POP.price3,'0') AS "PRICE3",
       COALESCE(POP.price4,'0') AS "PRICE4",
       COALESCE(POP.supply_unit_price,'0') AS "SUPPLY_UNIT_PRICE",
       COALESCE(POP.supply_unit_vat_price,'0') AS "SUPPLY_UNIT_VAT_PRICE",
       COALESCE(POP.supply_unit_vat_sum_price,'0') AS "SUPPLY_UNIT_VAT_SUM_PRICE",
       COALESCE(POP.real_supply_price,'0') AS "REAL_SUPPLY_PRICE",
       POP.remark AS "REMARK",
       POP.ld_part_objid AS "LD_PART_OBJID",
       COALESCE(POP.total_order_qty,'0') AS "TOTAL_ORDER_QTY",
       COALESCE(POP.stock_qty,'0') AS "STOCK_QTY",
       COALESCE(POP.real_order_qty,'0') AS "REAL_ORDER_QTY",
       (SELECT SUM(COALESCE(DH.delivery_qty,'0')::numeric) FROM delivery_history DH WHERE DH.purchase_order_part_objid = POP.objid) AS "TOTAL_DELIVERY_QTY",
       (SELECT SUM(COALESCE(DH.defect_qty,'0')::numeric) FROM delivery_history DH WHERE DH.purchase_order_part_objid = POP.objid) AS "TOTAL_DEFECT_QTY"
     FROM purchase_order_part POP
       JOIN purchase_order_master POM ON POM.objid = POP.purchase_order_master_objid
       LEFT OUTER JOIN part_mng PM ON POP.part_objid = PM.objid::text
     WHERE POP.purchase_order_master_objid::text = $1
     ORDER BY PM.part_no NULLS LAST, POP.regdate DESC`,
    [String(objId)],
  );

  // 동시발주 슬레이브 건들 (마스터의 경우만) — 같은 multi_master_objid를 가진 형제들
  const slaves =
    info.MULTI_MASTER_YN === "Y"
      ? await queryRows(
          `SELECT S.objid::text AS "OBJID",
             S.purchase_order_no AS "PURCHASE_ORDER_NO",
             S.partner_objid AS "PARTNER_OBJID",
             (SELECT supply_name FROM admin_supply_mng WHERE objid::text = S.partner_objid LIMIT 1) AS "PARTNER_NAME",
             S.contract_mgmt_objid::text AS "CONTRACT_MGMT_OBJID",
             (SELECT COALESCE(project_no, contract_no) FROM project_mgmt WHERE objid = S.contract_mgmt_objid LIMIT 1) AS "PROJECT_NO",
             S.unit_code AS "UNIT_CODE",
             S.delivery_plan_date AS "DELIVERY_PLAN_DATE",
             S.delivery_plan_qty AS "DELIVERY_PLAN_QTY",
             COALESCE(S.total_price,'0') AS "TOTAL_PRICE",
             S.status AS "STATUS"
           FROM purchase_order_master S
           WHERE S.multi_master_objid::text = $1
             AND S.objid::text != $1
           ORDER BY S.regdate`,
          [String(objId)],
        )
      : [];

  return NextResponse.json({ success: true, data: info, PARTS: parts, SLAVES: slaves });
}
