import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import { S3Client, ListBucketsCommand } from '@aws-sdk/client-s3'; import { createUserFolderStructure, listUserObjects } from '@/lib/s3'; // Import the configured S3 client from lib/s3.ts import { s3Client as configuredS3Client } from '@/lib/s3'; // Cache for folder lists const folderCache = new Map(); const CACHE_TTL = 5 * 60 * 1000; // 5 minutes export async function GET() { try { const session = await getServerSession(authOptions); if (!session?.user?.id) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const userId = session.user.id; // Check if we have cached folders for this user const cachedData = folderCache.get(userId); if (cachedData && (Date.now() - cachedData.timestamp < CACHE_TTL)) { return NextResponse.json({ status: 'ready', folders: cachedData.folders }); } // Check S3 connectivity using the configured client try { // Simple check by listing buckets await configuredS3Client.send(new ListBucketsCommand({})); } catch (error) { console.error('S3 connectivity check failed:', error); return NextResponse.json({ error: 'S3 storage service is not accessible', status: 'error' }, { status: 503 }); } // List the user's base folders try { // Standard folder list for the user const standardFolders = ['notes', 'diary', 'health', 'contacts']; let userFolders: string[] = []; // Try to list existing folders for (const folder of standardFolders) { try { const files = await listUserObjects(userId, folder); if (files.length > 0 || folder === 'notes') { userFolders.push(folder); } } catch (error) { console.error(`Error checking folder ${folder}:`, error); } } // If no folders found, create the standard structure if (userFolders.length === 0) { await createUserFolderStructure(userId); userFolders = standardFolders; } // Convert to Pascal case for backwards compatibility with NextCloud const formattedFolders = userFolders.map(folder => folder.charAt(0).toUpperCase() + folder.slice(1) ); // Update cache folderCache.set(userId, { folders: formattedFolders, timestamp: Date.now() }); return NextResponse.json({ status: 'ready', folders: formattedFolders }); } catch (error) { console.error('Error fetching user folders:', error); return NextResponse.json({ error: 'Failed to fetch folders', status: 'error' }, { status: 500 }); } } catch (error) { console.error('Error in storage status check:', error); return NextResponse.json({ error: 'Internal server error', status: 'error' }, { status: 500 }); } }