Neah/app/api/mail/mark-read/route.ts
2025-04-25 17:13:49 +02:00

91 lines
2.6 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { getImapClient } from '@/lib/imap';
import { ImapFlow } from 'imapflow';
export async function POST(request: Request) {
let client: ImapFlow | null = null;
try {
// Get the session and validate it
const session = await getServerSession(authOptions);
console.log('Session:', session); // Debug log
if (!session?.user?.id) {
console.error('No session or user ID found');
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// Get the request body
const { emailId, isRead } = await request.json();
console.log('Request body:', { emailId, isRead }); // Debug log
if (!emailId || typeof isRead !== 'boolean') {
console.error('Invalid request parameters:', { emailId, isRead });
return NextResponse.json(
{ error: 'Invalid request parameters' },
{ status: 400 }
);
}
// Get the current folder from the request URL
const url = new URL(request.url);
const folder = url.searchParams.get('folder') || 'INBOX';
console.log('Folder:', folder); // Debug log
try {
// Initialize IMAP client with user credentials
client = await getImapClient();
if (!client) {
console.error('Failed to initialize IMAP client');
return NextResponse.json(
{ error: 'Failed to initialize email client' },
{ status: 500 }
);
}
await client.connect();
await client.mailboxOpen(folder);
// Fetch the email to get its UID
const message = await client.fetchOne(emailId.toString(), {
uid: true,
flags: true
});
if (!message) {
console.error('Email not found:', emailId);
return NextResponse.json(
{ error: 'Email not found' },
{ status: 404 }
);
}
// Update the flags
if (isRead) {
await client.messageFlagsAdd(message.uid.toString(), ['\\Seen'], { uid: true });
} else {
await client.messageFlagsRemove(message.uid.toString(), ['\\Seen'], { uid: true });
}
return NextResponse.json({ success: true });
} finally {
if (client) {
try {
await client.logout();
} catch (e) {
console.error('Error during logout:', e);
}
}
}
} catch (error) {
console.error('Error marking email as read:', error);
return NextResponse.json(
{ error: 'Failed to mark email as read' },
{ status: 500 }
);
}
}