File size: 2,806 Bytes
cc276cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

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 });
    }
}