import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import { prisma } from '@/lib/prisma'; import { getMailboxes } from '@/lib/services/email-service'; import { ImapFlow } from 'imapflow'; import { cacheImapSession, getCachedImapSession } from '@/lib/redis'; export async function POST() { // Verify auth const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json( { error: 'Unauthorized' }, { status: 401 } ); } const userId = session.user.id; const results = { success: false, userId, accountsProcessed: 0, foldersFound: 0, accounts: [] as any[] }; try { // Get all accounts for this user const accounts = await prisma.mailCredentials.findMany({ where: { userId }, select: { id: true, email: true, password: true, host: true, port: true } }); if (accounts.length === 0) { return NextResponse.json({ success: false, error: 'No email accounts found' }); } // Process each account for (const account of accounts) { try { // Connect to IMAP server for this account const client = new ImapFlow({ host: account.host, port: account.port, secure: true, auth: { user: account.email, pass: account.password, }, logger: false, tls: { rejectUnauthorized: false } }); await client.connect(); // Get folders for this account const folders = await getMailboxes(client); // Store the results results.accounts.push({ id: account.id, email: account.email, folderCount: folders.length, folders }); results.foldersFound += folders.length; results.accountsProcessed++; // Get existing session data const existingSession = await getCachedImapSession(userId); // Update the Redis cache with the folders await cacheImapSession(userId, { ...(existingSession || { lastActive: Date.now() }), mailboxes: folders, lastVisit: Date.now() }); // Close connection await client.logout(); } catch (error) { results.accounts.push({ id: account.id, email: account.email, error: error instanceof Error ? error.message : 'Unknown error' }); } } results.success = results.accountsProcessed > 0; return NextResponse.json(results); } catch (error) { return NextResponse.json( { success: false, error: 'Failed to fix folders', details: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 } ); } }