import { NextRequest, NextResponse } from "next/server";
import { execute, queryOne } 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 body = await req.json();
  const {
    objid,
    actionType,
    itemName,
    itemDetail,
    makerObjid,
    unit,
    unitPrice,
    costPrice,
    isTaxFree,
    imageUrl,
    attributes,
    status,
    maxOrderQty,
    isHidden,
    requiresDelivery,
    vendorObjid,
  } = body;
  const maxQty = maxOrderQty == null || maxOrderQty === "" ? null : Number(maxOrderQty);
  const hidden = isHidden === "Y" ? "Y" : "N";
  const reqDelivery = requiresDelivery === "Y" ? "Y" : "N";

  if (!itemName) {
    return NextResponse.json({ success: false, message: "품목명은 필수입니다." }, { status: 400 });
  }

  // 품목명 앞의 'M' / 'M ' 접두는 자동 제거 (면세 표시는 is_tax_free 컬럼에서 관리)
  const cleanName = String(itemName).replace(/^M\s+/, "").trim();

  // 면세 여부는 사용자 명시 선택 그대로 사용 (자동 추론 X)
  const taxFree = isTaxFree === "Y" ? "Y" : "N";

  if (actionType === "regist") {
    const newId = createObjectId();
    const itemCode = await genItemCode();
    await execute(
      `INSERT INTO momo_items (
         objid, item_code, item_name, item_detail, maker_objid, vendor_objid,
         unit, unit_price, cost_price, is_tax_free, image_url, attributes, status,
         max_order_qty, is_hidden, requires_delivery,
         is_del, regdate, regid
       ) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12::jsonb,$13,$14,$15,$16,'N',NOW(),$17)`,
      [newId, itemCode, cleanName, itemDetail ?? null, makerObjid ?? null, vendorObjid ?? null,
       unit ?? "EA", Number(unitPrice ?? 0), Number(costPrice ?? 0),
       taxFree, imageUrl ?? null,
       attributes ? JSON.stringify(attributes) : null,
       status ?? "ACTIVE",
       maxQty, hidden, reqDelivery,
       userId]
    );
    return NextResponse.json({ success: true, objId: newId, itemCode });
  }

  if (!objid) return NextResponse.json({ success: false, message: "objid 누락" }, { status: 400 });
  await execute(
    `UPDATE momo_items SET
       item_name=$2, item_detail=$3, maker_objid=$4, unit=$5,
       unit_price=$6, cost_price=$7, is_tax_free=$8, image_url=$9,
       attributes=$10::jsonb, status=$11,
       max_order_qty=$12, is_hidden=$13, requires_delivery=$14,
       vendor_objid=$15,
       update_date=NOW(), update_id=$16
     WHERE objid=$1`,
    [objid, cleanName, itemDetail ?? null, makerObjid ?? null, unit ?? "EA",
     Number(unitPrice ?? 0), Number(costPrice ?? 0),
     taxFree, imageUrl ?? null,
     attributes ? JSON.stringify(attributes) : null,
     status ?? "ACTIVE",
     maxQty, hidden, reqDelivery,
     vendorObjid ?? null,
     userId]
  );
  return NextResponse.json({ success: true, objId: objid });
}

async function genItemCode(): Promise<string> {
  const today = new Date();
  const ymd = `${today.getFullYear()}${String(today.getMonth() + 1).padStart(2, "0")}${String(today.getDate()).padStart(2, "0")}`;
  const prefix = `ITM-${ymd}-`;
  const row = await queryOne<{ MAX_NO: string }>(
    `SELECT COALESCE(MAX(item_code), '') AS "MAX_NO" FROM momo_items WHERE item_code LIKE $1 || '%'`,
    [prefix]
  );
  const last = row?.MAX_NO ?? "";
  const lastNum = last ? Number(last.replace(prefix, "")) || 0 : 0;
  return prefix + String(lastNum + 1).padStart(4, "0");
}
