import { NextRequest, NextResponse } from 'next/server';
import { readFile } from 'fs/promises';
import { join } from 'path';
import { existsSync } from 'fs';

export async function GET(
  request: NextRequest,
  { params }: { params: { path: string[] } }
) {
  try {
    const filePath = params.path.join('/');
    
    // In production, files are in /app/uploads (Docker volume)
    // In development, files are in public/uploads
    const uploadsDir = process.env.NODE_ENV === 'production' 
      ? join(process.cwd(), 'uploads')
      : join(process.cwd(), 'public', 'uploads');
      
    const fullPath = join(uploadsDir, filePath);
    
    // Security check: ensure file is within uploads directory
    if (!fullPath.startsWith(uploadsDir)) {
      return new NextResponse('Forbidden', { status: 403 });
    }
    
    if (!existsSync(fullPath)) {
      return new NextResponse('File not found', { status: 404 });
    }
    
    const fileBuffer = await readFile(fullPath);
    
    // Get file extension for content type
    const ext = filePath.split('.').pop()?.toLowerCase();
    const contentType = getContentType(ext || '');
    
    return new NextResponse(fileBuffer, {
      headers: {
        'Content-Type': contentType,
        'Cache-Control': 'public, max-age=31536000, immutable',
      },
    });
  } catch (error) {
    console.error('Error serving file:', error);
    return new NextResponse('Internal Server Error', { status: 500 });
  }
}

function getContentType(ext: string): string {
  const mimeTypes: Record<string, string> = {
    'jpg': 'image/jpeg',
    'jpeg': 'image/jpeg',
    'png': 'image/png',
    'gif': 'image/gif',
    'webp': 'image/webp',
    'svg': 'image/svg+xml',
    'pdf': 'application/pdf',
    'txt': 'text/plain',
    'json': 'application/json',
    'zip': 'application/zip',
    'csv': 'text/csv',
  };
  
  return mimeTypes[ext] || 'application/octet-stream';
} 