// 공지 푸시 발송 — 선택한 사용자(userIds) 에게 푸시. URL 은 자체 공지 페이지(/m/notices/[id]).
import { NextRequest, NextResponse } from "next/server";
import { execute } from "@/lib/db";
import { requireMomoAdmin } from "@/lib/momo-guard";
import { sendPush, ensurePushTable } from "@/lib/push";
import { ensureNoticesTable } from "@/lib/notices";

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  await ensurePushTable();
  await ensureNoticesTable();

  const body = await req.json().catch(() => ({}));
  const { noticeObjid, title, message, url, userIds, sendAll, groupNames } = body as {
    noticeObjid?: string;
    title?: string;
    message?: string;
    url?: string;
    userIds?: string[];
    sendAll?: boolean;
    groupNames?: string[];
  };
  if (!title || !title.trim()) {
    return NextResponse.json({ success: false, message: "제목은 필수입니다." }, { status: 400 });
  }
  const targets = Array.isArray(userIds) ? userIds.filter(Boolean) : [];
  if (!sendAll && targets.length === 0) {
    return NextResponse.json({ success: false, message: "수신자를 선택하세요." }, { status: 400 });
  }

  const targetUrl = url && url.trim() !== "" ? url
    : noticeObjid ? `/m/notices/${noticeObjid}`
    : "/m/orders/new";

  const res = await sendPush(
    { title: title.trim(), body: (message ?? "").slice(0, 240), url: targetUrl, tag: noticeObjid ? `notice-${noticeObjid}` : undefined },
    sendAll ? undefined : targets
  );

  // 발송 통계 + 수신자 이력 기록 (공지가 있으면)
  if (noticeObjid) {
    await execute(
      `UPDATE momo_notices
          SET sent_count = COALESCE(sent_count,0) + $2,
              failed_count = COALESCE(failed_count,0) + $3,
              recipient_user_ids = $4::text[],
              recipient_count = $5,
              group_names = $6::text[]
        WHERE objid = $1`,
      [noticeObjid, res.sent, res.failed,
       sendAll ? [] : targets,
       sendAll ? -1 : targets.length,
       Array.isArray(groupNames) ? groupNames : []]
    ).catch(() => {});
  }

  console.log(`[notices/send-push] notice=${noticeObjid ?? "-"} title="${title}" targets=${sendAll ? "ALL" : targets.length} sent=${res.sent} failed=${res.failed}`);
  return NextResponse.json({ success: true, sent: res.sent, failed: res.failed });
}
