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?.user?.email) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const nextcloudUrl = process.env.NEXTCLOUD_URL; const clientId = process.env.NEXTCLOUD_CLIENT_ID; const clientSecret = process.env.NEXTCLOUD_CLIENT_SECRET; if (!nextcloudUrl || !clientId || !clientSecret) { console.error('Missing Nextcloud configuration'); return NextResponse.json( { error: 'Nextcloud configuration is missing' }, { status: 500 } ); } // First, get a Nextcloud OIDC token using client credentials const tokenResponse = await fetch(`${nextcloudUrl}/index.php/apps/oauth2/api/v1/token`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`, }, body: new URLSearchParams({ grant_type: 'client_credentials', scope: 'ocs', }), }); if (!tokenResponse.ok) { console.error('Failed to get Nextcloud token:', { status: tokenResponse.status, statusText: tokenResponse.statusText, }); return NextResponse.json({ error: 'Nextcloud authentication failed' }, { status: 401 }); } const { access_token } = await tokenResponse.json(); // Now try to access the Mail app using the Nextcloud token const response = await fetch(`${nextcloudUrl}/ocs/v2.php/apps/mail/api/v1/accounts`, { headers: { 'Authorization': `Bearer ${access_token}`, 'Accept': 'application/json', 'OCS-APIRequest': 'true', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', }, }); 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 data = await response.json(); const accounts = data?.ocs?.data || []; // For now, return a success response with an empty array 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 } ); } }