// 푸시 구독 해제 — endpoint 지정 시 그 구독만, 없으면 현재 사용자 전체
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { requireMomoUser } from "@/lib/momo-guard";
import { ensurePushTable } from "@/lib/push";

export async function POST(req: NextRequest) {
  const r = await requireMomoUser();
  if (r instanceof NextResponse) return r;
  await ensurePushTable();

  const body = await req.json().catch(() => ({}));
  const endpoint = body?.endpoint as string | undefined;
  const userId = r.user.objid || r.user.userId;

  if (endpoint) {
    await pool.query(`DELETE FROM momo_push_subscriptions WHERE endpoint = $1`, [endpoint]);
  } else {
    await pool.query(`DELETE FROM momo_push_subscriptions WHERE user_id = $1`, [userId]);
  }
  return NextResponse.json({ success: true });
}
