File size: 1,632 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

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();
    console.log(`[DELETE_MSG] Request received to delete message ${messageId} in chat ${chatId} by user ${userId}.`);

    if (!chatId || !messageId || !userId) {
        console.error('[DELETE_MSG] Missing required fields.');
        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()) {
            console.log(`[DELETE_MSG] Message ${messageId} already deleted or never existed.`);
            return NextResponse.json({ success: true, message: 'Message already deleted.' });
        }

        // Simplified logic: Just remove the message. The client-side logic should prevent unauthorized deletion attempts.
        // Complex logic about delivery status can be unreliable and cause errors.
        await messageRef.remove();
        console.log(`[DELETE_MSG] Message ${messageId} in chat ${chatId} was successfully deleted by trigger from user ${userId}.`);
        
        return NextResponse.json({ success: true, message: 'Message 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 });
    }
}