// 창고 이동 통계 — momo_stock_moves 의 ref_type='TRANSFER' OUT 행 기준 + cost_price 로 금액 산정
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 | undefined;
  const dateTo   = body.dateTo as string | undefined;

  // 본사(HQ_*) → 김포(KIMPO_*) 이동만 합산 — 사용자 요구
  const conditions: string[] = [
    "SM.ref_type = 'TRANSFER'",
    "SM.move_type = 'OUT'",
    "SW.wh_type LIKE 'HQ_%'",
    "TW.wh_type LIKE 'KIMPO_%'",
  ];
  const params: unknown[] = [];
  let i = 1;
  if (dateFrom) { conditions.push(`SM.regdate >= $${i++}::date`); params.push(dateFrom); }
  if (dateTo)   { conditions.push(`SM.regdate < ($${i++}::date + 1)`); params.push(dateTo); }

  const rows = await queryRows(
    `SELECT
       SM.objid                                AS "OBJID",
       TO_CHAR(SM.regdate, 'YYYY-MM-DD HH24:MI') AS "MOVED_AT",
       I.item_code                             AS "ITEM_CODE",
       I.item_name                             AS "ITEM_NAME",
       I.unit                                  AS "UNIT",
       I.cost_price                            AS "COST_PRICE",
       ABS(SM.qty)                             AS "QTY",
       ABS(SM.qty) * COALESCE(I.cost_price, 0) AS "AMOUNT",
       SW.wh_name                              AS "FROM_WH",
       SW.wh_code                              AS "FROM_CODE",
       TW.wh_name                              AS "TO_WH",
       TW.wh_code                              AS "TO_CODE",
       SM.memo                                 AS "MEMO",
       SM.regid                                AS "REGID",
       U.user_name                             AS "REG_USER_NAME"
     FROM momo_stock_moves SM
     LEFT JOIN momo_items I       ON I.objid = SM.item_objid
     LEFT JOIN momo_warehouses SW ON SW.objid = SM.wh_objid
     LEFT JOIN momo_warehouses TW ON TW.objid::text = SM.ref_objid
     LEFT JOIN user_info U        ON U.user_id = SM.regid
     WHERE ${conditions.join(" AND ")}
     ORDER BY SM.regdate DESC
     LIMIT 500`,
    params
  );

  // 합계
  const totalQty = rows.reduce((a, r) => a + Number(r.QTY), 0);
  const totalAmt = rows.reduce((a, r) => a + Number(r.AMOUNT), 0);

  return NextResponse.json({
    RESULTLIST: rows,
    TOTAL_CNT: rows.length,
    TOTAL_QTY: totalQty,
    TOTAL_AMOUNT: totalAmt,
  });
}
