import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import { getEmails } from '@/lib/services/email-service'; import { invalidateFolderCache } from '@/lib/redis'; import { refreshEmailsInBackground } from '@/lib/services/prefetch-service'; /** * API endpoint to force refresh email data * This is useful when the user wants to manually refresh or * when the app detects that it's been a while since the last refresh */ export async function POST(request: Request) { try { // Authenticate user const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json( { error: "Not authenticated" }, { status: 401 } ); } // Extract folder and account ID from request body const { folder = 'INBOX', accountId } = await request.json(); // CRITICAL FIX: Proper folder and account ID handling let normalizedFolder: string; let effectiveAccountId: string; if (folder.includes(':')) { // Extract parts if folder already has a prefix const parts = folder.split(':'); const folderAccountId = parts[0]; normalizedFolder = parts[1]; // If explicit accountId is provided, it takes precedence effectiveAccountId = accountId || folderAccountId; } else { // No prefix in folder name normalizedFolder = folder; effectiveAccountId = accountId || 'default'; } console.log(`[API] Refreshing folder=${normalizedFolder}, accountId=${effectiveAccountId}`); // First invalidate the cache for this folder with the effective account ID await invalidateFolderCache(session.user.id, effectiveAccountId, normalizedFolder); // Then trigger a background refresh with explicit account ID refreshEmailsInBackground(session.user.id, normalizedFolder, 1, 20, effectiveAccountId); // Also prefetch page 2 if this is the inbox if (normalizedFolder === 'INBOX') { refreshEmailsInBackground(session.user.id, normalizedFolder, 2, 20, effectiveAccountId); } return NextResponse.json({ success: true, message: `Refresh scheduled for folder: ${folder}` }); } catch (error) { console.error('Error scheduling refresh:', error); return NextResponse.json( { error: "Failed to schedule refresh" }, { status: 500 } ); } }