// 창고별 재고 현황 — 7개 창고 × 활성 품목 매트릭스
// 발주수량 = 보유 재고 (momo_stocks.qty)
// 여유분  = 보유 재고 - 입금 전 진행 중 발주의 출고예정 수량 (해당 창고 기준)
import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";

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

  const body = await req.json().catch(() => ({}));
  const dateFrom = (body.dateFrom as string) || "";  // YYYY-MM-DD
  const dateTo   = (body.dateTo as string) || "";

  // 1) 창고 7개 (wh_code 순)
  const warehouses = await queryRows<{ OBJID: string; WH_CODE: string; WH_NAME: string }>(
    `SELECT objid AS "OBJID", wh_code AS "WH_CODE", wh_name AS "WH_NAME"
       FROM momo_warehouses
      WHERE COALESCE(is_del,'N') != 'Y'
      ORDER BY wh_code`
  );

  // 2) 품목 + 창고별 stock + 기간 내 발주(예정/완료) 수량
  // 발주수량 = 기간 내 status IN (REQUESTED/APPROVED/INVOICED/PAID) 의 ITEM 수량 합
  // 여유분  = 현재고 - 발주수량  (음수면 부족)
  const dateConds: string[] = ["COALESCE(O.is_del,'N') != 'Y'", "COALESCE(OI.kind, 'ITEM') = 'ITEM'",
                               "O.status IN ('REQUESTED','APPROVED','INVOICED','PAID')"];
  const params: unknown[] = [];
  if (dateFrom) { params.push(dateFrom); dateConds.push(`O.order_date >= $${params.length}::date`); }
  if (dateTo)   { params.push(dateTo);   dateConds.push(`O.order_date <= $${params.length}::date`); }

  const rows = await queryRows<{
    ITEM_OBJID: string; ITEM_CODE: string; ITEM_NAME: string;
    WH_OBJID: string; WH_CODE: string;
    STOCK_QTY: string; PENDING_QTY: string;
  }>(
    `WITH stock AS (
       SELECT item_objid, wh_objid, qty
         FROM momo_stocks
     ),
     pending AS (
       SELECT OI.item_objid,
              COALESCE(U.default_wh_objid::text, (SELECT objid FROM momo_warehouses WHERE wh_code='WH001')) AS wh_objid,
              SUM(OI.qty) AS qty
         FROM momo_order_items OI
         JOIN momo_orders O ON O.objid = OI.order_objid
         LEFT JOIN user_info U ON U.user_id = O.customer_objid
        WHERE ${dateConds.join(" AND ")}
        GROUP BY OI.item_objid, COALESCE(U.default_wh_objid::text, (SELECT objid FROM momo_warehouses WHERE wh_code='WH001'))
     )
     SELECT
       I.objid       AS "ITEM_OBJID",
       I.item_code   AS "ITEM_CODE",
       I.item_name   AS "ITEM_NAME",
       W.objid       AS "WH_OBJID",
       W.wh_code     AS "WH_CODE",
       COALESCE(s.qty, 0)  AS "STOCK_QTY",
       COALESCE(p.qty, 0)  AS "PENDING_QTY"
     FROM momo_items I
     CROSS JOIN momo_warehouses W
     LEFT JOIN stock   s ON s.item_objid = I.objid AND s.wh_objid = W.objid
     LEFT JOIN pending p ON p.item_objid = I.objid AND p.wh_objid = W.objid
     WHERE COALESCE(I.is_del,'N') != 'Y'
       AND COALESCE(W.is_del,'N') != 'Y'
       AND COALESCE(I.is_hidden,'N') != 'Y'
     ORDER BY I.item_name, W.wh_code`,
    params
  );

  // 품목별 매트릭스로 정리 — 클라가 쓰기 쉽게
  type Matrix = {
    ITEM_OBJID: string; ITEM_CODE: string; ITEM_NAME: string;
    STOCK: Record<string, number>;
    AVAILABLE: Record<string, number>;
    TOTAL_STOCK: number;
    TOTAL_PENDING: number;
  };
  const byItem = new Map<string, Matrix>();
  for (const r of rows) {
    const stockQty = Number(r.STOCK_QTY);
    const pendingQty = Number(r.PENDING_QTY);
    const avail = stockQty - pendingQty;
    if (!byItem.has(r.ITEM_OBJID)) {
      byItem.set(r.ITEM_OBJID, {
        ITEM_OBJID: r.ITEM_OBJID, ITEM_CODE: r.ITEM_CODE, ITEM_NAME: r.ITEM_NAME,
        STOCK: {}, AVAILABLE: {}, TOTAL_STOCK: 0, TOTAL_PENDING: 0,
      });
    }
    const m = byItem.get(r.ITEM_OBJID)!;
    m.STOCK[r.WH_CODE] = stockQty;
    m.AVAILABLE[r.WH_CODE] = avail;
    m.TOTAL_STOCK += stockQty;
    m.TOTAL_PENDING += pendingQty;
  }

  // 재고가 한 창고라도 있거나 진행중 발주가 있는 품목만 노출
  const items = Array.from(byItem.values()).filter(
    (m) => m.TOTAL_STOCK > 0 || m.TOTAL_PENDING > 0
  );

  return NextResponse.json({
    WAREHOUSES: warehouses,
    ITEMS: items,
    TOTAL_CNT: items.length,
  });
}
