import { NextRequest, NextResponse } from "next/server";
import { execute, queryOne } from "@/lib/db";
import { createObjectId } from "@/lib/utils";
import { requireMomoAdmin } from "@/lib/momo-guard";

// 다음 자동 코드 생성: WH001, WH002 ... — 가장 큰 숫자 + 1
async function nextWhCode(): Promise<string> {
  const row = await queryOne<{ MAX_CODE: string | null }>(
    `SELECT MAX(wh_code) AS "MAX_CODE" FROM momo_warehouses WHERE wh_code ~ '^WH[0-9]+$'`
  );
  const max = row?.MAX_CODE;
  const nextNum = max ? parseInt(max.replace(/^WH/, ""), 10) + 1 : 1;
  return `WH${String(nextNum).padStart(3, "0")}`;
}

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

  const { objid, actionType, whName, location, whType } = await req.json();
  if (!whName) {
    return NextResponse.json({ success: false, message: "창고명은 필수입니다." }, { status: 400 });
  }
  if (actionType === "regist") {
    const id = createObjectId();
    const code = await nextWhCode();
    await execute(
      `INSERT INTO momo_warehouses (objid, wh_code, wh_name, location, wh_type, regdate)
       VALUES ($1,$2,$3,$4,$5,NOW())`,
      [id, code, whName, location ?? null, whType ?? "STOCK"]
    );
    return NextResponse.json({ success: true, objId: id, whCode: code });
  }
  // 수정 시 wh_code 는 손대지 않음
  await execute(
    `UPDATE momo_warehouses SET wh_name=$2, location=$3, wh_type=$4 WHERE objid=$1`,
    [objid, whName, location ?? null, whType ?? "STOCK"]
  );
  return NextResponse.json({ success: true });
}
