// 수신자 그룹 멤버 일괄 교체 (전체 삭제 후 새로 INSERT)
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
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 { groupObjid, userIds } = await req.json().catch(() => ({}));
  if (!groupObjid) return NextResponse.json({ success: false, message: "groupObjid 필수" }, { status: 400 });
  const ids = Array.isArray(userIds) ? userIds.filter(Boolean) : [];

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query(`DELETE FROM momo_recipient_group_members WHERE group_objid = $1`, [groupObjid]);
    if (ids.length > 0) {
      const values = ids.map((_, i) => `($1, $${i + 2}, NOW())`).join(",");
      await client.query(
        `INSERT INTO momo_recipient_group_members (group_objid, user_id, added_at) VALUES ${values}`,
        [groupObjid, ...ids]
      );
    }
    await client.query("COMMIT");
    return NextResponse.json({ success: true, count: ids.length });
  } catch (err) {
    await client.query("ROLLBACK");
    console.error("[notices/groups/members/save]", err);
    return NextResponse.json({ success: false, message: "저장 중 오류" }, { status: 500 });
  } finally {
    client.release();
  }
}
