// 수신자 그룹 목록 + 각 그룹의 멤버 수
import { NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { ensureNoticesTable } from "@/lib/notices";

export async function POST() {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  await ensureNoticesTable();
  const rows = await queryRows(
    `SELECT G.objid AS "OBJID", G.name AS "NAME", G.description AS "DESCRIPTION",
            TO_CHAR(G.regdate,'YYYY-MM-DD') AS "REGDATE",
            COALESCE((SELECT COUNT(*)::int FROM momo_recipient_group_members M
                       WHERE M.group_objid = G.objid), 0) AS "MEMBER_CNT",
            COALESCE((SELECT ARRAY_AGG(M.user_id) FROM momo_recipient_group_members M
                       WHERE M.group_objid = G.objid), ARRAY[]::text[]) AS "MEMBER_IDS"
       FROM momo_recipient_groups G
      WHERE COALESCE(G.is_del,'N') != 'Y'
      ORDER BY G.name`
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
