// 푸시 공지 저장 (admin) — 신규/수정 모두 처리. 발송은 별도 send-push 라우트에서.
import { NextRequest, NextResponse } from "next/server";
import { execute, queryOne } from "@/lib/db";
import { createObjectId } from "@/lib/utils";
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 userId = g.user.objid || g.user.userId;

  const body = await req.json().catch(() => ({}));
  const { objid, title, body: text, imageUrl, url } = body as {
    objid?: string; title?: string; body?: string; imageUrl?: string; url?: string;
  };
  if (!title || !title.trim()) {
    return NextResponse.json({ success: false, message: "제목은 필수입니다." }, { status: 400 });
  }

  if (objid) {
    const cur = await queryOne(`SELECT 1 FROM momo_notices WHERE objid = $1`, [objid]);
    if (!cur) return NextResponse.json({ success: false, message: "공지를 찾을 수 없습니다." }, { status: 404 });
    await execute(
      `UPDATE momo_notices SET title=$2, body=$3, image_url=$4, url=$5 WHERE objid=$1`,
      [objid, title.trim(), text ?? null, imageUrl || null, url || null]
    );
    return NextResponse.json({ success: true, objId: objid });
  }

  const newId = createObjectId();
  await execute(
    `INSERT INTO momo_notices (objid, title, body, image_url, url, regdate, regid)
     VALUES ($1, $2, $3, $4, $5, NOW(), $6)`,
    [newId, title.trim(), text ?? null, imageUrl || null, url || null, userId]
  );
  return NextResponse.json({ success: true, objId: newId });
}
