// 푸시알림 발송이력 — 보낸 공지 전체 + 수신자 이름 조회.
//   각 행마다 recipient_user_ids 의 user_id 들을 user_info 와 조인해서 이름 배열로 반환.
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 N.objid AS "OBJID", N.title AS "TITLE", N.body AS "BODY",
            N.image_url AS "IMAGE_URL", N.url AS "URL",
            TO_CHAR(N.regdate,'YYYY-MM-DD HH24:MI') AS "REGDATE",
            N.regid AS "REGID",
            COALESCE(N.sent_count,0)        AS "SENT_COUNT",
            COALESCE(N.failed_count,0)      AS "FAILED_COUNT",
            COALESCE(N.recipient_count,0)   AS "RECIPIENT_COUNT",
            COALESCE(N.recipient_user_ids, ARRAY[]::text[]) AS "RECIPIENT_USER_IDS",
            COALESCE(N.group_names,        ARRAY[]::text[]) AS "GROUP_NAMES",
            COALESCE((
              SELECT ARRAY_AGG(COALESCE(U.user_name, X.uid))
                FROM UNNEST(COALESCE(N.recipient_user_ids, ARRAY[]::text[])) AS X(uid)
                LEFT JOIN user_info U ON U.user_id = X.uid
            ), ARRAY[]::text[]) AS "RECIPIENT_NAMES"
       FROM momo_notices N
      WHERE COALESCE(N.is_del,'N') != 'Y'
      ORDER BY N.regdate DESC
      LIMIT 300`
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
