// 재고 이동 (A창고 → B창고). 출발창고 차감 + 도착창고 가산 + 이동 로그 2건
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { createObjectId } from "@/lib/utils";
import { requireMomoAdmin } from "@/lib/momo-guard";

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

  const { fromWhObjid, toWhObjid, itemObjid, qty, memo } = await req.json().catch(() => ({})) as {
    fromWhObjid?: string; toWhObjid?: string; itemObjid?: string; qty?: number; memo?: string;
  };

  if (!fromWhObjid || !toWhObjid || !itemObjid || !qty || qty <= 0) {
    return NextResponse.json({ success: false, message: "출발창고/도착창고/품목/수량을 입력하세요." }, { status: 400 });
  }
  if (fromWhObjid === toWhObjid) {
    return NextResponse.json({ success: false, message: "출발창고와 도착창고가 같습니다." }, { status: 400 });
  }

  const client = await pool.connect();
  try {
    await client.query("BEGIN");

    // 출발 재고 잠금 + 충분 여부 확인
    const cur = await client.query<{ qty: number }>(
      `SELECT qty::int FROM momo_stocks WHERE wh_objid=$1 AND item_objid=$2 FOR UPDATE`,
      [fromWhObjid, itemObjid]
    );
    const have = cur.rows[0]?.qty ?? 0;
    if (have < qty) {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: `출발창고 재고가 부족합니다. (현재고 ${have})` }, { status: 400 });
    }

    // 출발 차감
    await client.query(
      `UPDATE momo_stocks SET qty = qty - $3, update_date = NOW()
       WHERE wh_objid = $1 AND item_objid = $2`,
      [fromWhObjid, itemObjid, qty]
    );

    // 도착 가산 (없으면 생성)
    await client.query(
      `INSERT INTO momo_stocks (objid, wh_objid, item_objid, qty, update_date)
       VALUES ($1, $2, $3, $4, NOW())
       ON CONFLICT (wh_objid, item_objid) DO UPDATE
         SET qty = momo_stocks.qty + EXCLUDED.qty, update_date = NOW()`,
      [createObjectId(), toWhObjid, itemObjid, qty]
    );

    // 이동 로그 — 출발(OUT)에 ref_objid=도착창고, 도착(IN)에 ref_objid=출발창고
    // (history 조회 시 ref_objid 로 상대 창고 join 해서 "→/←" 표기)
    await client.query(
      `INSERT INTO momo_stock_moves (objid, wh_objid, item_objid, move_type, qty, ref_type, ref_objid, memo, regdate, regid)
       VALUES ($1, $2, $3, 'OUT', $4, 'TRANSFER', $9, $5, NOW(), $6),
              ($7, $8, $3, 'IN',  $4, 'TRANSFER', $2, $5, NOW(), $6)`,
      [createObjectId(), fromWhObjid, itemObjid, qty, memo ?? null, userId, createObjectId(), toWhObjid, toWhObjid]
    );

    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: `${qty} 단위 이동 완료` });
  } catch (err) {
    await client.query("ROLLBACK").catch(() => {});
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[transfer]", err);
    return NextResponse.json({ success: false, message: msg }, { status: 500 });
  } finally {
    client.release();
  }
}
