import { NextRequest, NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ filename: string }> }
) {
  try {
    const { filename } = await params;
    
    // Construct the path to the thumbnail file
    const thumbnailPath = path.join(process.cwd(), 'public', 'thumbnails', filename);
    
    // Check if the file exists
    if (!fs.existsSync(thumbnailPath)) {
      return NextResponse.json({ error: 'Thumbnail not found' }, { status: 404 });
    }
    
    // Read the file
    const fileBuffer = fs.readFileSync(thumbnailPath);
    
    // Return the image with appropriate headers
    return new NextResponse(fileBuffer, {
      headers: {
        'Content-Type': 'image/png',
        'Cache-Control': 'public, max-age=31536000, immutable',
      },
    });
  } catch (error) {
    console.error('Error serving thumbnail:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  }
}
