import { NextRequest, NextResponse } from 'next/server'; import { adminFirestore, adminMessaging } from '@/lib/firebase-admin'; export async function POST(req: NextRequest) { console.log("[/api/notify] Received a POST request."); let recipientUidForError: string | null = null; try { const { recipientUid, senderUid, title, body, icon, chatId } = await req.json(); recipientUidForError = recipientUid; console.log("[/api/notify] Request body parsed:", { recipientUid, senderUid, title, body, icon, chatId }); // The crucial check to prevent self-notifications if (senderUid && recipientUid === senderUid) { console.log(`[FCM Notify] Skipped: Sender and recipient are the same user (${senderUid}).`); return NextResponse.json({ success: true, message: 'Sender is recipient, notification skipped.' }); } if (!recipientUid || !title || !body || !chatId) { console.log("[/api/notify] Missing required fields."); return NextResponse.json({ error: 'Missing required fields: recipientUid, title, body, chatId' }, { status: 400 }); } console.log(`[/api/notify] Fetching user document for UID: ${recipientUid}`); const userDoc = await adminFirestore.collection('users').doc(recipientUid).get(); if (!userDoc.exists) { console.log(`[/api/notify] Recipient user not found: ${recipientUid}`); return NextResponse.json({ error: 'Recipient user not found' }, { status: 404 }); } const fcmToken = userDoc.data()?.fcmToken; console.log(`[/api/notify] Found FCM token: ${fcmToken ? 'Yes' : 'No'}`); if (!fcmToken) { console.log(`[/api/notify] Notification not sent: User ${recipientUid} does not have an FCM token.`); return NextResponse.json({ success: true, message: 'User has no FCM token.' }); } const message = { token: fcmToken, notification: { title: title, body: body, }, webpush: { notification: { icon: '/favicon.ico', // Always use a static, known-good icon }, fcm_options: { link: `/?chatId=${chatId}` } }, }; console.log("[/api/notify] Prepared message payload:", message); console.log("[/api/notify] Sending message via FCM..."); const response = await adminMessaging.send(message); console.log('[/api/notify] Successfully sent message:', response); return NextResponse.json({ success: true, messageId: response }); } catch (error: any) { console.error('[/api/notify] CRITICAL ERROR:', error); let errorMessage = 'Internal Server Error'; let statusCode = 500; if (error.code === 'messaging/invalid-argument') { errorMessage = 'Invalid argument provided for FCM message.'; statusCode = 400; } else if (error.code === 'messaging/registration-token-not-registered') { errorMessage = `The FCM token for user ${recipientUidForError} is no longer valid. It might be expired.`; if (recipientUidForError) { await adminFirestore.collection('users').doc(recipientUidForError).update({ fcmToken: '' }); } statusCode = 404; } else if (error.code === 'messaging/invalid-registration-token') { errorMessage = `Invalid FCM registration token for user ${recipientUidForError}.`; if (recipientUidForError) { await adminFirestore.collection('users').doc(recipientUidForError).update({ fcmToken: '' }); } statusCode = 400; } return NextResponse.json({ error: 'Failed to send notification', details: errorMessage, rawError: error.message }, { status: statusCode }); } }