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

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

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

  const conditions: string[] = ["COALESCE(I.is_del,'N') != 'Y'"];
  const params: unknown[] = [];
  let i = 1;
  if (whObjid) {
    conditions.push(`S.wh_objid = $${i++}`);
    params.push(whObjid);
  }
  if (keyword) {
    conditions.push(`(I.item_name ILIKE '%' || $${i} || '%' OR I.item_code ILIKE '%' || $${i} || '%')`);
    params.push(keyword);
    i++;
  }

  const rows = await queryRows(
    `SELECT
       S.objid       AS "OBJID",
       W.objid       AS "WH_OBJID",
       W.wh_code     AS "WH_CODE",
       W.wh_name     AS "WH_NAME",
       I.objid       AS "ITEM_OBJID",
       I.item_code   AS "ITEM_CODE",
       I.item_name   AS "ITEM_NAME",
       I.unit        AS "UNIT",
       I.is_tax_free AS "IS_TAX_FREE",
       S.qty         AS "QTY",
       TO_CHAR(S.update_date, 'YYYY-MM-DD HH24:MI') AS "UPDATE_DATE"
     FROM momo_stocks S
     JOIN momo_warehouses W ON S.wh_objid = W.objid
     JOIN momo_items I ON S.item_objid = I.objid
     WHERE ${conditions.join(" AND ")}
     ORDER BY W.wh_code, I.item_name`,
    params
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
