import { NextRequest, NextResponse } from "next/server"; import { supabase } from "@/lib/supabase"; export const dynamic = "force-dynamic"; export const runtime = "nodejs"; export async function POST(request: NextRequest) { try { const { userId, subscription } = await request.json(); console.log("Subscribe request received:", { userId, subscription }); if (!userId || !subscription) { console.error("Missing userId or subscription"); return NextResponse.json({ error: "User ID and subscription are required" }, { status: 400 }); } const { endpoint, keys } = subscription; console.log("Subscription data:", { endpoint: !!endpoint, keys: !!keys }); if (!endpoint || !keys?.auth || !keys?.p256dh) { console.error("Invalid subscription format:", { endpoint: !!endpoint, auth: !!keys?.auth, p256dh: !!keys?.p256dh }); return NextResponse.json({ error: "Invalid subscription format" }, { status: 400 }); } // Check if this subscription already exists const { data: existing, error: checkError } = await supabase .from("push_subscriptions") .select("id") .eq("endpoint", endpoint) .eq("user_id", userId) .maybeSingle(); if (checkError) { console.error("Error checking existing subscription:", checkError); } if (existing) { console.log("Subscription already exists"); return NextResponse.json({ success: true, message: "Already subscribed" }); } // Insert new subscription const { error, data } = await supabase.from("push_subscriptions").insert({ user_id: userId, endpoint, auth_key: keys.auth, p256dh_key: keys.p256dh, }).select(); if (error) { console.error("Insert subscription error:", error); return NextResponse.json({ error: "Failed to save subscription: " + error.message }, { status: 500 }); } console.log("Subscription saved successfully:", data); return NextResponse.json({ success: true, message: "Subscribed to push notifications" }); } catch (error: any) { console.error("Subscribe to push notifications error:", error); return NextResponse.json({ error: error.message || "Internal server error" }, { status: 500 }); } }