import { NextRequest, NextResponse } from 'next/server'; import { adminFirestore, adminMessaging } from '@/lib/firebase-admin'; export async function POST(req: NextRequest) { const { recipientUid, title, body, icon, chatId } = await req.json(); if (!recipientUid || !title || !body || !chatId) { return NextResponse.json({ error: 'Missing required fields: recipientUid, title, body, chatId' }, { status: 400 }); } try { const userDoc = await adminFirestore.collection('users').doc(recipientUid).get(); if (!userDoc.exists) { return NextResponse.json({ error: 'Recipient user not found' }, { status: 404 }); } const fcmToken = userDoc.data()?.fcmToken; if (!fcmToken) { console.log(`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}` } }, }; const response = await adminMessaging.send(message); console.log('Successfully sent message:', response); return NextResponse.json({ success: true, messageId: response }); } catch (error: any) { console.error('Error sending FCM message:', 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 ${recipientUid} is no longer valid. It might be expired.`; await adminFirestore.collection('users').doc(recipientUid).update({ fcmToken: '' }); statusCode = 404; } else if (error.code === 'messaging/invalid-registration-token') { errorMessage = `Invalid FCM registration token for user ${recipientUid}.`; await adminFirestore.collection('users').doc(recipientUid).update({ fcmToken: '' }); statusCode = 400; } return NextResponse.json({ error: 'Failed to send notification', details: errorMessage }, { status: statusCode }); } }