// 거래처(회원) 정보/권한 수정 — 관리자 전용
// 본인 정보 수정용 엔드포인트는 별도 (/api/auth/profile)
import { NextRequest, NextResponse } from "next/server";
import { execute } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";

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

  const body = await req.json().catch(() => ({}));
  const {
    userId,
    userName,
    email,
    cellPhone,
    bizNo,
    ceoName,
    address,
    status,
    unlimitedQty,
    viewHidden,
  } = body as Record<string, string>;

  if (!userId) {
    return NextResponse.json({ success: false, message: "userId 누락" }, { status: 400 });
  }

  const unlimited = unlimitedQty === "Y" ? "Y" : "N";
  const view = viewHidden === "Y" ? "Y" : "N";

  await execute(
    `UPDATE user_info SET
       user_name     = COALESCE($2, user_name),
       email         = COALESCE($3, email),
       cell_phone    = COALESCE($4, cell_phone),
       biz_no        = COALESCE($5, biz_no),
       ceo_name      = COALESCE($6, ceo_name),
       address       = COALESCE($7, address),
       status        = COALESCE($8, status),
       unlimited_qty = $9,
       view_hidden   = $10
     WHERE user_id = $1 AND COALESCE(user_type, '') NOT IN ('A')`,
    [userId, userName ?? null, email ?? null, cellPhone ?? null, bizNo ?? null,
     ceoName ?? null, address ?? null, status ?? null, unlimited, view]
  );
  return NextResponse.json({ success: true });
}
