import { NextRequest, NextResponse } from "next/server";
import { queryOne, queryRows } from "@/lib/db";
import { requireMomoUser } from "@/lib/momo-guard";
import { getSupplierByBranch } from "@/lib/momo-branches";

export async function POST(req: NextRequest) {
  const r = await requireMomoUser();
  if (r instanceof NextResponse) return r;

  const { objid } = await req.json();
  if (!objid) return NextResponse.json({ success: false, message: "objid 누락" }, { status: 400 });

  const order = await queryOne<Record<string, unknown>>(
    `SELECT
       O.objid AS "OBJID", O.order_no AS "ORDER_NO",
       TO_CHAR(O.order_date,'YYYY-MM-DD') AS "ORDER_DATE",
       O.customer_objid AS "CUSTOMER_OBJID",
       U.user_name AS "COMPANY_NAME", U.email AS "EMAIL",
       U.ceo_name AS "CEO_NAME", U.biz_no AS "BIZ_NO",
       U.cell_phone AS "PHONE", U.address AS "ADDRESS",
       U.statement_branch AS "STATEMENT_BRANCH",
       O.status AS "STATUS", O.memo AS "MEMO",
       O.total_supply AS "TOTAL_SUPPLY", O.total_vat AS "TOTAL_VAT",
       O.total_amount AS "TOTAL_AMOUNT",
       O.total_taxfree AS "TOTAL_TAXFREE", O.total_taxable AS "TOTAL_TAXABLE",
       COALESCE(O.total_delivery, 0) AS "TOTAL_DELIVERY",
       COALESCE(O.total_charter, 0)  AS "TOTAL_CHARTER",
       O.invoice_no AS "INVOICE_NO",
       TO_CHAR(O.invoice_date,'YYYY-MM-DD') AS "INVOICE_DATE",
       O.paid_amount AS "PAID_AMOUNT",
       TO_CHAR(O.approve_date,'YYYY-MM-DD HH24:MI') AS "APPROVE_DATE",
       O.supplier_branch       AS "SUPPLIER_BRANCH",
       O.supplier_name         AS "SUPPLIER_NAME",
       O.supplier_ceo          AS "SUPPLIER_CEO",
       O.supplier_bank_account AS "SUPPLIER_BANK_ACCOUNT",
       O.supplier_phone        AS "SUPPLIER_PHONE",
       O.supplier_email        AS "SUPPLIER_EMAIL",
       O.supplier_biz_no       AS "SUPPLIER_BIZ_NO",
       O.supplier_address      AS "SUPPLIER_ADDRESS"
     FROM momo_orders O
     LEFT JOIN user_info U ON U.user_id = O.customer_objid
     WHERE O.objid = $1 AND COALESCE(O.is_del,'N') != 'Y'`,
    [objid]
  );
  if (!order) return NextResponse.json({ success: false, message: "발주를 찾을 수 없습니다." }, { status: 404 });

  if (r.user.role === "USER" && order.CUSTOMER_OBJID !== r.user.objid) {
    return NextResponse.json({ success: false, message: "조회 권한이 없습니다." }, { status: 403 });
  }

  const items = await queryRows(
    `SELECT
       OI.objid AS "OBJID", OI.seq AS "SEQ",
       OI.item_objid AS "ITEM_OBJID",
       OI.item_name_snap AS "ITEM_NAME",
       OI.unit_price AS "UNIT_PRICE",
       OI.qty AS "QTY",
       OI.is_tax_free AS "IS_TAX_FREE",
       OI.supply_amount AS "SUPPLY_AMOUNT",
       OI.vat_amount AS "VAT_AMOUNT",
       OI.total_amount AS "TOTAL_AMOUNT",
       COALESCE(OI.kind, 'ITEM') AS "KIND",
       OI.extra_label AS "EXTRA_LABEL",
       OI.remark AS "REMARK",
       I.unit AS "UNIT",
       I.image_url AS "IMAGE_URL",
       -- 현재고: 거래처에 default_wh_objid 가 있으면 그 창고 재고, 없으면 STOCK 류 전체 합
       -- (출고가 실제로 일어날 창고 기준 — approve 로직과 일관)
       COALESCE(
         CASE
           WHEN UD.default_wh_objid IS NOT NULL THEN
             (SELECT SUM(S.qty) FROM momo_stocks S
                WHERE S.item_objid = OI.item_objid
                  AND S.wh_objid = UD.default_wh_objid::text)
           ELSE
             (SELECT SUM(S.qty) FROM momo_stocks S
                JOIN momo_warehouses W ON W.objid = S.wh_objid
                WHERE S.item_objid = OI.item_objid
                  AND W.wh_type IN ('STOCK','HQ_STOCK','KIMPO_STOCK')
                  AND COALESCE(W.is_del,'N') != 'Y')
         END,
         0
       ) AS "STOCK_QTY"
     FROM momo_order_items OI
     LEFT JOIN momo_items I ON OI.item_objid = I.objid
     LEFT JOIN momo_orders OD ON OD.objid = OI.order_objid
     LEFT JOIN user_info UD ON UD.user_id = OD.customer_objid
     WHERE OI.order_objid = $1
     ORDER BY
       CASE COALESCE(OI.kind,'ITEM')
         WHEN 'DELIVERY' THEN 0
         WHEN 'CHARTER'  THEN 1
         ELSE 2
       END,
       OI.seq ASC`,
    [objid]
  );

  // 공급자(모모유통) 정보:
  //  - 출고요청 시점에 momo_orders.supplier_* 컬럼에 snapshot 박힘 → 그것을 사용
  //  - 옛 발주(snapshot 없음) 는 user_info.statement_branch + branches table 폴백
  const o = order as Record<string, unknown>;
  const supplier = o.SUPPLIER_BANK_ACCOUNT
    ? {
        CODE:         String(o.SUPPLIER_BRANCH ?? "HQ"),
        NAME:         String(o.SUPPLIER_NAME ?? "모모유통"),
        CEO:          String(o.SUPPLIER_CEO ?? ""),
        BANK_ACCOUNT: String(o.SUPPLIER_BANK_ACCOUNT ?? ""),
        PHONE:        String(o.SUPPLIER_PHONE ?? ""),
        EMAIL:        String(o.SUPPLIER_EMAIL ?? ""),
        BIZ_NO:       String(o.SUPPLIER_BIZ_NO ?? ""),
        ADDRESS:      String(o.SUPPLIER_ADDRESS ?? ""),
      }
    : await getSupplierByBranch(String(o.STATEMENT_BRANCH ?? "HQ"));

  return NextResponse.json({ success: true, order, items, supplier });
}
