// 수신자 그룹 생성/수정/삭제
//   action="delete" 면 soft-delete + 멤버 row 모두 제거
//   그 외(생성/수정)는 name/description upsert
import { NextRequest, NextResponse } from "next/server";
import { execute, queryOne } from "@/lib/db";
import { createObjectId } from "@/lib/utils";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { ensureNoticesTable } from "@/lib/notices";

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

  const body = await req.json().catch(() => ({}));
  const { objid, name, description, action } = body as {
    objid?: string; name?: string; description?: string; action?: "delete";
  };

  if (action === "delete") {
    if (!objid) return NextResponse.json({ success: false, message: "objid 필수" }, { status: 400 });
    await execute(`UPDATE momo_recipient_groups SET is_del='Y' WHERE objid=$1`, [objid]);
    await execute(`DELETE FROM momo_recipient_group_members WHERE group_objid=$1`, [objid]);
    return NextResponse.json({ success: true });
  }

  if (!name || !name.trim()) {
    return NextResponse.json({ success: false, message: "그룹명은 필수입니다." }, { status: 400 });
  }

  if (objid) {
    const cur = await queryOne(`SELECT 1 FROM momo_recipient_groups WHERE objid = $1`, [objid]);
    if (!cur) return NextResponse.json({ success: false, message: "그룹을 찾을 수 없습니다." }, { status: 404 });
    await execute(
      `UPDATE momo_recipient_groups SET name=$2, description=$3 WHERE objid=$1`,
      [objid, name.trim(), description ?? null]
    );
    return NextResponse.json({ success: true, objId: objid });
  }
  const newId = createObjectId();
  await execute(
    `INSERT INTO momo_recipient_groups (objid, name, description, regdate, regid)
     VALUES ($1, $2, $3, NOW(), $4)`,
    [newId, name.trim(), description ?? null, userId]
  );
  return NextResponse.json({ success: true, objId: newId });
}
