import { NextRequest, NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";

// 재고 입출고 이력 (momo_stock_moves)
export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;

  const body = await req.json().catch(() => ({}));
  const { whObjid, itemObjid, moveType, dateFrom, dateTo, keyword } = body as {
    whObjid?: string;
    itemObjid?: string;
    moveType?: string;
    dateFrom?: string;
    dateTo?: string;
    keyword?: string;
  };

  const conditions = ["1=1"];
  const params: unknown[] = [];
  let i = 1;

  if (whObjid) {
    conditions.push(`SM.wh_objid = $${i++}`);
    params.push(whObjid);
  }
  if (itemObjid) {
    conditions.push(`SM.item_objid = $${i++}`);
    params.push(itemObjid);
  }
  if (moveType) {
    conditions.push(`SM.move_type = $${i++}`);
    params.push(moveType);
  }
  if (dateFrom) {
    conditions.push(`SM.regdate >= $${i++}::date`);
    params.push(dateFrom);
  }
  if (dateTo) {
    conditions.push(`SM.regdate < ($${i++}::date + INTERVAL '1 day')`);
    params.push(dateTo);
  }
  if (keyword) {
    conditions.push(`(I.item_name ILIKE '%' || $${i} || '%' OR I.item_code ILIKE '%' || $${i} || '%')`);
    params.push(keyword);
    i++;
  }

  const rows = await queryRows(
    `SELECT
       SM.objid          AS "OBJID",
       W.wh_name         AS "WH_NAME",
       W.wh_code         AS "WH_CODE",
       I.item_code       AS "ITEM_CODE",
       I.item_name       AS "ITEM_NAME",
       I.unit            AS "UNIT",
       SM.move_type      AS "MOVE_TYPE",
       CASE SM.move_type
         WHEN 'IN'       THEN '입고'
         WHEN 'OUT'      THEN '출고'
         WHEN 'ADJ'      THEN '재고조정'
         WHEN 'TRANSFER' THEN '이동'
         ELSE SM.move_type
       END               AS "MOVE_TYPE_NAME",
       SM.qty            AS "QTY",
       SM.ref_type       AS "REF_TYPE",
       CASE SM.ref_type
         WHEN 'INBOUND'     THEN '입고'
         WHEN 'PROCUREMENT' THEN '매입발주'
         WHEN 'ORDER'       THEN '출고'
         WHEN 'TRANSFER'    THEN '이동'
         WHEN 'ADJUST'      THEN '재고조정'
         ELSE COALESCE(SM.ref_type, '-')
       END               AS "REF_TYPE_LABEL",
       SM.ref_objid      AS "REF_OBJID",
       -- TRANSFER 의 경우 ref_objid 는 상대 창고 — 그 창고명 join
       CASE WHEN SM.ref_type = 'TRANSFER'
            THEN CW.wh_name
            ELSE NULL
       END               AS "COUNTER_WH_NAME",
       SM.memo           AS "MEMO",
       SM.regid          AS "REGID",
       TO_CHAR(SM.regdate, 'YYYY-MM-DD HH24:MI') AS "REGDATE"
     FROM momo_stock_moves SM
     LEFT JOIN momo_warehouses W  ON SM.wh_objid  = W.objid
     LEFT JOIN momo_warehouses CW ON SM.ref_objid = CW.objid::text AND SM.ref_type = 'TRANSFER'
     LEFT JOIN momo_items I       ON SM.item_objid = I.objid
     WHERE ${conditions.join(" AND ")}
     ORDER BY SM.regdate DESC
     LIMIT 500`,
    params
  );

  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
