import { NextResponse } from 'next/server'; import { ImapFlow } from 'imapflow'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import { prisma } from '@/lib/prisma'; import { saveUserEmailCredentials, testEmailConnection } from '@/lib/services/email-service'; import { prefetchUserEmailData } from '@/lib/services/prefetch-service'; import { invalidateUserEmailCache, getCachedEmailCredentials } from '@/lib/redis'; export async function POST(request: Request) { try { const session = await getServerSession(authOptions); console.log('Session in mail login:', session); if (!session?.user?.id) { console.error('No user ID in session'); return NextResponse.json( { error: 'Unauthorized' }, { status: 401 } ); } // Verify user exists console.log('Checking for user with ID:', session.user.id); const user = await prisma.user.findUnique({ where: { id: session.user.id } }); console.log('User found in database:', user); if (!user) { console.error('User not found in database'); return NextResponse.json( { error: 'User not found' }, { status: 404 } ); } const { email, password, host, port } = await request.json(); if (!email || !password || !host || !port) { return NextResponse.json( { error: 'Missing required fields' }, { status: 400 } ); } // Test connection before saving const connectionSuccess = await testEmailConnection({ email, password, host, port: parseInt(port) }); if (!connectionSuccess) { return NextResponse.json( { error: 'Failed to connect to email server. Please check your credentials.' }, { status: 401 } ); } // Invalidate all cached data for this user await invalidateUserEmailCache(session.user.id); // Save credentials using the service that handles both database and Redis await saveUserEmailCredentials(session.user.id, { email, password, host, port: parseInt(port) }); // Start prefetching email data in the background prefetchUserEmailData(session.user.id).catch(err => { console.error('Background prefetch error:', err); }); return NextResponse.json({ success: true }); } catch (error) { console.error('Error in login handler:', error); return NextResponse.json( { error: 'An unexpected error occurred' }, { status: 500 } ); } } export async function GET() { try { const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json( { error: 'Unauthorized' }, { status: 401 } ); } // First try to get from Redis cache let credentials = await getCachedEmailCredentials(session.user.id); // If not in cache, get from database if (!credentials) { credentials = await prisma.mailCredentials.findUnique({ where: { userId: session.user.id }, select: { email: true, host: true, port: true } }); } else { // Remove password from response const { password, ...safeCredentials } = credentials; credentials = safeCredentials; } if (!credentials) { return NextResponse.json( { error: 'No stored credentials found' }, { status: 404 } ); } return NextResponse.json(credentials); } catch (error) { return NextResponse.json( { error: 'Failed to retrieve credentials' }, { status: 500 } ); } }