// 푸시 공지 수신자 후보 — 현재 푸시 구독한 사용자 목록.
//   구독이 없는 사용자에게는 보내봐야 도착하지 않으므로 구독자만 보여준다.
import { NextResponse } from "next/server";
import { queryRows } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { ensurePushTable } from "@/lib/push";

export async function POST() {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  await ensurePushTable();
  const rows = await queryRows(
    `SELECT s.user_id                AS "USER_ID",
            COALESCE(u.user_name,'') AS "USER_NAME",
            COALESCE(u.user_type,'') AS "USER_TYPE",
            COALESCE(u.user_type,'')='A' AS "IS_ADMIN",
            COALESCE(u.dept_name,'') AS "DEPT_NAME",
            MAX(s.user_agent)        AS "USER_AGENT",
            TO_CHAR(MAX(s.last_seen),'YYYY-MM-DD HH24:MI') AS "LAST_SEEN",
            COUNT(*)::int            AS "DEVICE_CNT"
       FROM momo_push_subscriptions s
       LEFT JOIN user_info u ON u.user_id = s.user_id
      GROUP BY s.user_id, u.user_name, u.user_type, u.dept_name
      ORDER BY u.user_name NULLS LAST, s.user_id`
  );
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
