import { getServerSession } from "next-auth"; import { authOptions } from "@/app/api/auth/[...nextauth]/route"; import { NextResponse } from "next/server"; // Helper function to create/refresh token async function ensureValidToken(baseUrl: string, userId: string, currentToken: string | null) { try { // Try to create a new token const tokenResponse = await fetch(`${baseUrl}/api/v1/users.createToken`, { method: 'POST', headers: { 'X-Auth-Token': currentToken || '', 'X-User-Id': userId, }, }); if (tokenResponse.ok) { const tokenData = await tokenResponse.json(); return { token: tokenData.data.authToken, userId: tokenData.data.userId, }; } console.error('Failed to create/refresh token:', tokenResponse.status); return null; } catch (error) { console.error('Error creating/refreshing token:', error); return null; } } export async function GET(request: Request) { const session = await getServerSession(authOptions); if (!session) { console.error('No session found'); return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401, headers: { 'Content-Type': 'application/json' }, }); } console.log('Session data:', { hasToken: !!session.rocketChatToken, hasUserId: !!session.rocketChatUserId, tokenLength: session.rocketChatToken?.length, userIdLength: session.rocketChatUserId?.length, username: session.user?.username }); if (!session.rocketChatToken || !session.rocketChatUserId) { console.error('Missing Rocket.Chat credentials in session:', { hasToken: !!session.rocketChatToken, hasUserId: !!session.rocketChatUserId, username: session.user?.username }); return new Response(JSON.stringify({ error: 'Missing Rocket.Chat credentials' }), { status: 401, headers: { 'Content-Type': 'application/json' }, }); } try { const baseUrl = process.env.NEXT_PUBLIC_IFRAME_PAROLE_URL?.split('/channel')[0]; if (!baseUrl) { console.error('Failed to get Rocket.Chat base URL'); return new Response(JSON.stringify({ error: 'Server configuration error' }), { status: 500, headers: { 'Content-Type': 'application/json' }, }); } // Ensure we have valid token const tokenInfo = await ensureValidToken( baseUrl, session.rocketChatUserId || '', session.rocketChatToken || null ); if (!tokenInfo) { return new Response(JSON.stringify({ error: 'Failed to authenticate with Rocket.Chat' }), { status: 401, headers: { 'Content-Type': 'application/json' }, }); } // Get user's subscriptions with new token const subscriptionsResponse = await fetch(`${baseUrl}/api/v1/subscriptions.get`, { headers: { 'X-Auth-Token': tokenInfo.token, 'X-User-Id': tokenInfo.userId, }, }); if (!subscriptionsResponse.ok) { console.error('Failed to get subscriptions:', subscriptionsResponse.status); return new Response(JSON.stringify({ error: 'Failed to get subscriptions' }), { status: subscriptionsResponse.status, headers: { 'Content-Type': 'application/json' }, }); } const subscriptionsData = await subscriptionsResponse.json(); const userSubscriptions = subscriptionsData.update.filter((subscription: any) => subscription.t === 'd' ? subscription.rid.includes(tokenInfo.userId) : true ); const messages: any[] = []; const processedRooms = new Set(); for (const subscription of userSubscriptions) { if (messages.length >= 6 || processedRooms.has(subscription.rid)) continue; processedRooms.add(subscription.rid); try { const messagesResponse = await fetch( `${baseUrl}/api/v1/chat.getMessage`, { method: 'POST', headers: { 'X-Auth-Token': tokenInfo.token, 'X-User-Id': tokenInfo.userId, 'Content-Type': 'application/json', }, body: JSON.stringify({ msgId: subscription.lastMessage?._id, roomId: subscription.rid, }), }); if (!messagesResponse.ok) continue; const messageData = await messagesResponse.json(); if (messageData.message) { messages.push({ ...messageData.message, roomName: subscription.fname || subscription.name || 'Direct Message', roomType: subscription.t, unread: subscription.unread || 0, userMentions: subscription.userMentions || 0, alert: subscription.alert || false }); } } catch (error) { console.error(`Error fetching message for room ${subscription.rid}`); continue; } } // Sort messages by timestamp (newest first) and limit to 6 messages.sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime()); const limitedMessages = messages.slice(0, 6); return new Response(JSON.stringify({ messages: limitedMessages }), { status: 200, headers: { 'Content-Type': 'application/json' }, }); } catch (error) { console.error('Error fetching messages'); return new Response(JSON.stringify({ error: 'Internal server error' }), { status: 500, headers: { 'Content-Type': 'application/json' }, }); } }