import { NextResponse, NextRequest } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; export async function GET(req: NextRequest) { try { const session = await getServerSession(authOptions); if (!session?.accessToken) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const nextcloudUrl = process.env.NEXTCLOUD_URL; if (!nextcloudUrl) { console.error('Missing Nextcloud URL'); return NextResponse.json( { error: 'Nextcloud configuration is missing' }, { status: 500 } ); } // First, try to get the user's Nextcloud ID using the Keycloak token const userInfoResponse = await fetch(`${nextcloudUrl}/ocs/v2.php/cloud/user`, { headers: { 'Authorization': `Bearer ${session.accessToken}`, 'Accept': 'application/json', 'OCS-APIRequest': 'true', }, }); if (!userInfoResponse.ok) { console.error('Failed to get user info:', { status: userInfoResponse.status, statusText: userInfoResponse.statusText, url: userInfoResponse.url }); if (userInfoResponse.status === 401) { return NextResponse.json({ error: 'Nextcloud authentication failed' }, { status: 401 }); } return NextResponse.json( { error: "L'application Mail n'est pas disponible sur Nextcloud. Veuillez contacter votre administrateur." }, { status: 404 } ); } const userInfo = await userInfoResponse.json(); const userId = userInfo?.ocs?.data?.id; if (!userId) { console.error('Failed to get user ID from Nextcloud'); return NextResponse.json( { error: "L'application Mail n'est pas disponible sur Nextcloud. Veuillez contacter votre administrateur." }, { status: 404 } ); } // Now try to access the Mail app const response = await fetch(`${nextcloudUrl}/index.php/apps/mail/api/accounts`, { headers: { 'Authorization': `Bearer ${session.accessToken}`, 'Accept': 'application/json', 'Content-Type': 'application/json', }, }); if (!response.ok) { console.error('Mail app check failed:', { status: response.status, statusText: response.statusText, url: response.url }); if (response.status === 401) { return NextResponse.json({ error: 'Nextcloud authentication failed' }, { status: 401 }); } return NextResponse.json( { error: "L'application Mail n'est pas disponible sur Nextcloud. Veuillez contacter votre administrateur." }, { status: 404 } ); } const accounts = await response.json(); // For now, return a success response with an empty array // We'll implement the actual message fetching once we confirm the correct endpoint return NextResponse.json([]); } catch (error) { console.error('Error checking Mail app:', error); return NextResponse.json( { error: "L'application Mail n'est pas disponible sur Nextcloud. Veuillez contacter votre administrateur." }, { status: 404 } ); } }