// 공급업체 등록/수정 — supply_mng 재사용
import { NextRequest, NextResponse } from "next/server";
import { execute } 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.userId;

  const { objid, actionType, vendorName, contact, phone, bizNo, email, address } = await req.json();
  if (!vendorName) return NextResponse.json({ success: false, message: "공급업체명 필수" }, { status: 400 });

  if (actionType === "regist") {
    const id = createObjectId();
    const code = "VND-" + id.slice(-6);
    await execute(
      `INSERT INTO supply_mng (objid, supply_code, supply_name, charge_user_name, supply_tel_no, reg_no, email, supply_address, status, reg_id, reg_date)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'active', $9, NOW())`,
      [id, code, vendorName, contact ?? null, phone ?? null, bizNo ?? null, email ?? null, address ?? null, userId]
    );
    return NextResponse.json({ success: true, objId: id });
  }
  await execute(
    `UPDATE supply_mng SET supply_name=$2, charge_user_name=$3, supply_tel_no=$4, reg_no=$5, email=$6, supply_address=$7 WHERE objid=$1`,
    [objid, vendorName, contact ?? null, phone ?? null, bizNo ?? null, email ?? null, address ?? null]
  );
  return NextResponse.json({ success: true });
}
