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()) { // Message might have been deleted by another recipient already, which is not an error. return NextResponse.json({ success: true, message: 'Message already deleted.' }); } const message = snapshot.val(); // --- SECURITY CHECK --- // Ensure the message has been delivered to the user requesting deletion. 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 }); } // Logic to determine if all recipients have received it. const participantsRef = adminDb.ref(`chats/${chatId}/participants`); const participantsSnap = await participantsRef.get(); if (!participantsSnap.exists()) { // If participants list is gone, it's safe to delete. 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 { // Not all have received it yet, so we don't delete. 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 }); } }