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

// Thumbnail sizes
const SIZES = {
  sm: 200,   // Small thumbnail for grids
  md: 400,   // Medium for cards
  lg: 800,   // Large for expanded views
};

type SizeKey = keyof typeof SIZES;

export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  try {
    const { path: pathParts } = await params;
    const url = new URL(req.url);
    const size = (url.searchParams.get('size') || 'md') as SizeKey;
    const width = SIZES[size] || SIZES.md;

    // Reconstruct the file path from path parts
    // Expected format: /api/thumbnail/uploads/rollId/filename.jpg?size=md
    const filePath = pathParts.join('/');
    const fullPath = path.join(process.cwd(), 'public', filePath);

    // Security: ensure path is within public/uploads
    const normalizedPath = path.normalize(fullPath);
    const uploadsDir = path.join(process.cwd(), 'public', 'uploads');
    if (!normalizedPath.startsWith(uploadsDir)) {
      return NextResponse.json({ error: 'Invalid path' }, { status: 403 });
    }

    // Check if file exists (use normalizedPath for all file operations)
    try {
      await fs.access(normalizedPath);
    } catch {
      return NextResponse.json({ error: 'File not found' }, { status: 404 });
    }

    // Generate thumbnail with sharp (use normalizedPath to prevent path traversal)
    const thumbnail = await sharp(normalizedPath)
      .resize(width, null, {
        fit: 'inside',
        withoutEnlargement: true,
      })
      .jpeg({ quality: 80, progressive: true })
      .toBuffer();

    // Return with aggressive caching (thumbnails don't change)
    return new NextResponse(thumbnail, {
      status: 200,
      headers: {
        'Content-Type': 'image/jpeg',
        'Cache-Control': 'public, max-age=31536000, immutable',
      },
    });
  } catch (error) {
    console.error('Thumbnail generation error:', error);
    return NextResponse.json(
      { error: 'Failed to generate thumbnail' },
      { status: 500 }
    );
  }
}
