import { NextResponse } from 'next/server'; import { getServerSession } from 'next-auth'; import { authOptions } from '@/app/api/auth/[...nextauth]/route'; import { ListBucketsCommand, ListObjectsV2Command } from '@aws-sdk/client-s3'; import { createUserFolderStructure } from '@/lib/s3'; // Import the configured S3 client and config from lib/s3.ts import { s3Client } from '@/lib/s3'; import { S3_CONFIG } from '@/lib/s3'; // Simple in-memory cache with consistent expiration const CACHE_TTL = 2 * 60 * 1000; // 2 minutes const folderCache = new Map(); 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; const cacheKey = `folders:${userId}`; // Check cache first const cachedData = folderCache.get(cacheKey); if (cachedData && (Date.now() - cachedData.timestamp < CACHE_TTL)) { console.log(`Using cached folders for user ${userId}`); return NextResponse.json({ status: 'ready', folders: cachedData.folders }); } // Verify S3 connectivity try { await s3Client.send(new ListBucketsCommand({})); } catch (error) { console.error('S3 connectivity issue:', error); return NextResponse.json({ status: 'error', error: 'Storage service is unavailable' }, { status: 503 }); } // List folders in the user's path try { // Using the user prefix to list all folders const prefix = `user-${userId}/`; const command = new ListObjectsV2Command({ Bucket: S3_CONFIG.bucket, Prefix: prefix, Delimiter: '/' }); const response = await s3Client.send(command); const prefixes = response.CommonPrefixes || []; // Extract folder names and convert to display format let folders = prefixes .map(prefix => { // Extract folder name from path (e.g., user-123/notes/ → notes) const folderName = prefix.Prefix?.split('/')[1] || ''; // Format folder name for display (capitalize first letter) return folderName.charAt(0).toUpperCase() + folderName.slice(1); }) .filter(Boolean); // Remove any empty strings console.log(`Found ${folders.length} folders for user ${userId}`); // If no folders, create the standard structure if (folders.length === 0) { console.log(`No folders found, creating structure for user ${userId}`); await createUserFolderStructure(userId); // Use standard folder list for display folders = ['Notes', 'Diary', 'Health', 'Contacts']; } // Update cache with the results folderCache.set(cacheKey, { folders, timestamp: Date.now() }); // Return the folder list return NextResponse.json({ status: 'ready', folders }); } catch (error) { console.error('Error listing folders:', error); return NextResponse.json({ status: 'error', error: 'Failed to list folders' }, { status: 500 }); } } catch (error) { console.error('Status endpoint error:', error); return NextResponse.json({ status: 'error', error: 'Internal server error' }, { status: 500 }); } }