83 lines
2.6 KiB
TypeScript
83 lines
2.6 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { authOptions } from '@/lib/auth';
|
|
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 {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
const { id: emailId } = params;
|
|
if (!emailId) {
|
|
return NextResponse.json({ error: 'Email ID is required' }, { status: 400 });
|
|
}
|
|
|
|
const { folder = 'INBOX', accountId, isRead = true } = await request.json();
|
|
|
|
// Extract account ID from folder name if present and none was explicitly provided
|
|
const folderAccountId = folder.includes(':') ? folder.split(':')[0] : accountId;
|
|
|
|
// Use the most specific account ID available
|
|
const effectiveAccountId = folderAccountId || accountId || 'default';
|
|
|
|
// Normalize folder name by removing account prefix if present
|
|
const normalizedFolder = folder.includes(':') ? folder.split(':')[1] : folder;
|
|
|
|
// Log operation details for debugging
|
|
console.log(`Marking email ${emailId} as ${isRead ? 'read' : 'unread'} in folder ${normalizedFolder} for account ${effectiveAccountId}`);
|
|
|
|
const success = await markEmailReadStatus(
|
|
session.user.id,
|
|
emailId,
|
|
isRead,
|
|
normalizedFolder,
|
|
effectiveAccountId
|
|
);
|
|
|
|
if (!success) {
|
|
return NextResponse.json(
|
|
{ error: 'Failed to mark email as read' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
|
|
return NextResponse.json({ success: true });
|
|
} catch (error) {
|
|
console.error('Error marking email as read:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Internal server error' },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|