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

// 발주서 상세 조회 (purchaseOrder.getPurchaseOrderMasterInfo 대응)
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 master = await queryOne(
    `SELECT POM.objid::text AS "OBJID",
       POM.purchase_order_no AS "PURCHASE_ORDER_NO",
       POM.title AS "TITLE",
       POM.type AS "TYPE",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = POM.type LIMIT 1), '') AS "TYPE_NAME",
       POM.order_type_cd AS "ORDER_TYPE_CD",
       POM.purchase_order_no_org AS "PURCHASE_ORDER_NO_ORG",
       POM.partner_objid AS "PARTNER_OBJID",
       COALESCE((SELECT supply_name FROM supply_mng WHERE objid::text = POM.partner_objid LIMIT 1), '') AS "PARTNER_NAME",
       POM.my_company_objid AS "MY_COMPANY_OBJID",
       POM.contract_mgmt_objid::text AS "CONTRACT_MGMT_OBJID",
       POM.unit_code AS "UNIT_CODE",
       POM.delivery_date AS "DELIVERY_DATE",
       POM.delivery_place AS "DELIVERY_PLACE",
       COALESCE((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",
       COALESCE((SELECT code_name FROM comm_code WHERE code_id = POM.payment_terms LIMIT 1), '') AS "PAYMENT_TERMS_NAME",
       POM.vat_method AS "VAT_METHOD",
       POM.remark AS "REMARK",
       POM.sales_mng_user_id AS "SALES_MNG_USER_ID",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = POM.sales_mng_user_id LIMIT 1), '') AS "SALES_MNG_USER_NAME",
       POM.total_supply_unit_price AS "TOTAL_SUPPLY_UNIT_PRICE",
       POM.total_supply_price AS "TOTAL_SUPPLY_PRICE",
       POM.total_real_supply_price AS "TOTAL_REAL_SUPPLY_PRICE",
       POM.discount_price AS "DISCOUNT_PRICE",
       POM.total_price AS "TOTAL_PRICE",
       POM.nego_rate AS "NEGO_RATE",
       POM.total_price_txt AS "TOTAL_PRICE_TXT",
       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_NAME",
       POM.project_no AS "PROJECT_NO",
       POM.writer AS "WRITER",
       COALESCE((SELECT user_name FROM user_info WHERE user_id = POM.writer LIMIT 1), '') AS "WRITER_NAME",
       TO_CHAR(POM.regdate, 'YYYY-MM-DD') AS "REGDATE"
     FROM purchase_order_master POM
     WHERE POM.objid::text = $1`,
    [objId]
  );

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

  // 부품 목록 조회
  const parts = await queryRows(
    `SELECT POP.objid::text AS "OBJID",
       POP.part_objid AS "PART_OBJID",
       POP.part_no AS "PART_NO",
       POP.part_name AS "PART_NAME",
       POP.spec AS "SPEC",
       POP.maker AS "MAKER",
       POP.unit AS "UNIT",
       POP.bom_qty AS "BOM_QTY",
       POP.qty AS "QTY",
       POP.order_qty AS "ORDER_QTY",
       POP.partner_price AS "PARTNER_PRICE",
       POP.price1 AS "PRICE1",
       POP.price2 AS "PRICE2",
       POP.price3 AS "PRICE3",
       POP.price4 AS "PRICE4",
       POP.supply_unit_price AS "SUPPLY_UNIT_PRICE",
       POP.supply_unit_vat_price AS "SUPPLY_UNIT_VAT_PRICE",
       POP.supply_unit_vat_sum_price AS "SUPPLY_UNIT_VAT_SUM_PRICE",
       POP.total_order_qty AS "TOTAL_ORDER_QTY",
       POP.stock_qty AS "STOCK_QTY",
       POP.real_order_qty AS "REAL_ORDER_QTY",
       POP.real_supply_price AS "REAL_SUPPLY_PRICE",
       POP.remark AS "REMARK"
     FROM purchase_order_part POP
     WHERE POP.purchase_order_master_objid = $1
     ORDER BY POP.part_no`,
    [objId]
  );

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