97 lines
2.8 KiB
TypeScript
97 lines
2.8 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { authOptions } from "@/app/api/auth/options";
|
|
import { markEmailReadStatus } from '@/lib/services/email-service';
|
|
import { invalidateEmailContentCache, invalidateFolderCache } from '@/lib/redis';
|
|
|
|
// 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,
|
|
context: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const session = await getServerSession(authOptions);
|
|
if (!session || !session.user?.id) {
|
|
return NextResponse.json(
|
|
{ error: "Not authenticated" },
|
|
{ status: 401 }
|
|
);
|
|
}
|
|
|
|
// Await params as per Next.js requirements
|
|
const params = await context.params;
|
|
const id = params?.id;
|
|
if (!id) {
|
|
return NextResponse.json(
|
|
{ error: "Missing email ID" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const { isRead, folder, accountId } = await request.json();
|
|
|
|
if (typeof isRead !== 'boolean') {
|
|
return NextResponse.json(
|
|
{ error: "Invalid 'isRead' parameter. Must be a boolean." },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const normalizedFolder = folder || "INBOX";
|
|
const effectiveAccountId = accountId || 'default';
|
|
|
|
// Use the email service to mark the email
|
|
const success = await markEmailReadStatus(
|
|
session.user.id,
|
|
id,
|
|
isRead,
|
|
normalizedFolder,
|
|
effectiveAccountId
|
|
);
|
|
|
|
if (!success) {
|
|
return NextResponse.json(
|
|
{ error: `Failed to ${isRead ? 'mark email as read' : 'mark email as unread'}` },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
|
|
// Invalidate cache for this email
|
|
await invalidateEmailContentCache(session.user.id, effectiveAccountId, id);
|
|
|
|
// Also invalidate folder cache to update unread counts
|
|
await invalidateFolderCache(session.user.id, effectiveAccountId, normalizedFolder);
|
|
|
|
return NextResponse.json({ success: true });
|
|
} catch (error: any) {
|
|
console.error("Error in mark-read API:", error);
|
|
return NextResponse.json(
|
|
{ error: "Internal server error", message: error.message },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|