| |
|
| | import { NextRequest, NextResponse } from 'next/server'; |
| | import { adminDb } from '@/lib/firebase-admin'; |
| |
|
| | export async function POST(req: NextRequest) { |
| | const { chatId, messageId, userId } = await req.json(); |
| |
|
| | if (!chatId || !messageId || !userId) { |
| | return NextResponse.json({ error: 'Missing required fields: chatId, messageId, userId' }, { status: 400 }); |
| | } |
| |
|
| | try { |
| | const messageRef = adminDb.ref(`chats/${chatId}/messages/${messageId}`); |
| | const snapshot = await messageRef.get(); |
| |
|
| | if (!snapshot.exists()) { |
| | |
| | return NextResponse.json({ success: true, message: 'Message already deleted.' }); |
| | } |
| |
|
| | const message = snapshot.val(); |
| | |
| | |
| | |
| | if (!message.deliveredTo || !message.deliveredTo[userId]) { |
| | console.warn(`[DELETE_MSG] Unauthorized attempt to delete message ${messageId} by user ${userId}. Message not yet delivered to them.`); |
| | return NextResponse.json({ error: 'Unauthorized: Cannot delete a message not yet delivered to you.' }, { status: 403 }); |
| | } |
| |
|
| | |
| | const participantsRef = adminDb.ref(`chats/${chatId}/participants`); |
| | const participantsSnap = await participantsRef.get(); |
| | if (!participantsSnap.exists()) { |
| | |
| | await messageRef.remove(); |
| | return NextResponse.json({ success: true, message: 'Message deleted as participants list is missing.' }); |
| | } |
| |
|
| | const participants = Object.keys(participantsSnap.val()); |
| | const deliveredUsers = Object.keys(message.deliveredTo); |
| | |
| | const allDelivered = participants.every(p => deliveredUsers.includes(p)); |
| |
|
| | if (allDelivered) { |
| | await messageRef.remove(); |
| | console.log(`[DELETE_MSG] Message ${messageId} deleted successfully as all recipients have received it.`); |
| | return NextResponse.json({ success: true, message: 'Message deleted.' }); |
| | } else { |
| | |
| | console.log(`[DELETE_MSG] Message ${messageId} not deleted yet. Waiting for other recipients.`); |
| | return NextResponse.json({ success: true, message: 'Message acknowledged, but not yet deleted.' }); |
| | } |
| |
|
| | } catch (error: any) { |
| | console.error('Error in delete-message endpoint:', error); |
| | return NextResponse.json({ error: 'Failed to process message deletion', details: error.message }, { status: 500 }); |
| | } |
| | } |
| |
|