import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import { markEmailReadStatus } from '@/lib/services/email-service'; // Global cache reference (will be moved to a proper cache solution in the future) declare global { var emailListCache: { [key: string]: { data: any, timestamp: number } }; } // Helper function to invalidate cache for a specific folder const invalidateCache = (userId: string, folder?: string) => { if (!global.emailListCache) return; Object.keys(global.emailListCache).forEach(key => { // If folder is provided, only invalidate that folder's cache if (folder) { if (key.includes(`${userId}:${folder}`)) { delete global.emailListCache[key]; } } else { // Otherwise invalidate all user's caches if (key.startsWith(`${userId}:`)) { delete global.emailListCache[key]; } } }); }; // Mark email as read export async function POST( request: Request, { params }: { params: { id: string } } ) { try { // Get session const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } // No need to await Promise.resolve(), params is already an object const { id: emailId } = params; if (!emailId) { return NextResponse.json({ error: 'Email ID is required' }, { status: 400 }); } try { // Use the email service to mark the email as read // First try with INBOX folder let success = await markEmailReadStatus(session.user.id, emailId, true, 'INBOX'); // If not found in INBOX, try to find it in other common folders if (!success) { const commonFolders = ['Sent', 'Drafts', 'Trash', 'Spam', 'Junk']; for (const folder of commonFolders) { success = await markEmailReadStatus(session.user.id, emailId, true, folder); if (success) { // If found in a different folder, invalidate that folder's cache invalidateCache(session.user.id, folder); break; } } } else { // Email found in INBOX, invalidate INBOX cache invalidateCache(session.user.id, 'INBOX'); } if (!success) { return NextResponse.json( { error: 'Email not found in any folder' }, { status: 404 } ); } return NextResponse.json({ success: true }); } catch (error) { console.error('Error marking email as read:', error); return NextResponse.json( { error: 'Failed to mark email as read' }, { status: 500 } ); } } catch (error) { console.error('Error marking email as read:', error); return NextResponse.json( { error: 'Failed to mark email as read' }, { status: 500 } ); } }