import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import { saveUserEmailCredentials, getUserEmailCredentials, testEmailConnection } from '@/lib/services/email-service'; import { prefetchUserEmailData } from '@/lib/services/prefetch-service'; import { cacheEmailCredentials, invalidateUserEmailCache, getCachedEmailCredentials } from '@/lib/redis'; import { prisma } from '@/lib/prisma'; export async function POST(request: Request) { try { // Authenticate user const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json( { error: 'Unauthorized' }, { status: 401 } ); } // Get credentials from request const { email, password, host, port } = await request.json(); // Validate required fields 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 as they are changing their credentials await invalidateUserEmailCache(session.user.id); // Create credentials object with required fields const credentials = { email, password, host, port: parseInt(port), secure: true // Default to secure connection }; // Save credentials in the database and Redis // Use email as the accountId since it's unique per user await saveUserEmailCredentials(session.user.id, email, credentials); // Start prefetching email data in the background // We don't await this to avoid blocking the response 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, 'default'); // 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 } ); } }