import { NextRequest, NextResponse } from 'next/server';
import { optimizeImage, generateResponsiveImages, convertToModernFormats, compressForWeb, getImageMetadata, calculateCompressionRatio, formatFileSize } from '@/lib/image-optimizer';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

/**
 * POST /api/images/optimize
 * Optimize uploaded image(s)
 */
export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData();
    const file = formData.get('file') as File;
    const action = formData.get('action') as string || 'optimize';
    const width = formData.get('width') ? parseInt(formData.get('width') as string) : undefined;
    const height = formData.get('height') ? parseInt(formData.get('height') as string) : undefined;
    const quality = formData.get('quality') ? parseInt(formData.get('quality') as string) : 80;
    const format = (formData.get('format') as 'jpeg' | 'png' | 'webp' | 'avif') || 'webp';

    if (!file) {
      return NextResponse.json(
        { error: 'No file provided' },
        { status: 400 }
      );
    }

    const arrayBuffer = await file.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);

    // Get original metadata
    const originalMetadata = await getImageMetadata(buffer);

    switch (action) {
      case 'optimize':
        const optimized = await optimizeImage(buffer, {
          width,
          height,
          quality,
          format,
        });

        const compressionRatio = calculateCompressionRatio(originalMetadata.size, optimized.size);

        return NextResponse.json({
          success: true,
          original: {
            size: originalMetadata.size,
            sizeFormatted: formatFileSize(originalMetadata.size),
            width: originalMetadata.width,
            height: originalMetadata.height,
            format: originalMetadata.format,
          },
          optimized: {
            size: optimized.size,
            sizeFormatted: formatFileSize(optimized.size),
            width: optimized.width,
            height: optimized.height,
            format: optimized.format,
          },
          compressionRatio: `${compressionRatio}%`,
          image: optimized.buffer.toString('base64'),
        });

      case 'responsive':
        const widths = [320, 640, 768, 1024, 1280, 1920];
        const responsiveImages = await generateResponsiveImages(buffer, widths);

        const variants = Array.from(responsiveImages.entries()).map(([width, img]) => ({
          width,
          size: img.size,
          sizeFormatted: formatFileSize(img.size),
          format: img.format,
          image: img.buffer.toString('base64'),
        }));

        return NextResponse.json({
          success: true,
          original: {
            size: originalMetadata.size,
            sizeFormatted: formatFileSize(originalMetadata.size),
            width: originalMetadata.width,
            height: originalMetadata.height,
            format: originalMetadata.format,
          },
          variants,
        });

      case 'modern-formats':
        const modernFormats = await convertToModernFormats(buffer, width);

        return NextResponse.json({
          success: true,
          original: {
            size: originalMetadata.size,
            sizeFormatted: formatFileSize(originalMetadata.size),
            width: originalMetadata.width,
            height: originalMetadata.height,
            format: originalMetadata.format,
          },
          formats: {
            webp: {
              size: modernFormats.webp.size,
              sizeFormatted: formatFileSize(modernFormats.webp.size),
              compressionRatio: `${calculateCompressionRatio(originalMetadata.size, modernFormats.webp.size)}%`,
              image: modernFormats.webp.buffer.toString('base64'),
            },
            avif: modernFormats.avif ? {
              size: modernFormats.avif.size,
              sizeFormatted: formatFileSize(modernFormats.avif.size),
              compressionRatio: `${calculateCompressionRatio(originalMetadata.size, modernFormats.avif.size)}%`,
              image: modernFormats.avif.buffer.toString('base64'),
            } : null,
            fallback: {
              size: modernFormats.fallback.size,
              sizeFormatted: formatFileSize(modernFormats.fallback.size),
              compressionRatio: `${calculateCompressionRatio(originalMetadata.size, modernFormats.fallback.size)}%`,
              image: modernFormats.fallback.buffer.toString('base64'),
            },
          },
        });

      case 'compress':
        const compressed = await compressForWeb(buffer);
        const compressRatio = calculateCompressionRatio(originalMetadata.size, compressed.size);

        return NextResponse.json({
          success: true,
          original: {
            size: originalMetadata.size,
            sizeFormatted: formatFileSize(originalMetadata.size),
            width: originalMetadata.width,
            height: originalMetadata.height,
            format: originalMetadata.format,
          },
          compressed: {
            size: compressed.size,
            sizeFormatted: formatFileSize(compressed.size),
            width: compressed.width,
            height: compressed.height,
            format: compressed.format,
            compressionRatio: `${compressRatio}%`,
          },
          image: compressed.buffer.toString('base64'),
        });

      case 'metadata':
        return NextResponse.json({
          success: true,
          metadata: {
            ...originalMetadata,
            sizeFormatted: formatFileSize(originalMetadata.size),
          },
        });

      default:
        return NextResponse.json(
          { error: 'Invalid action' },
          { status: 400 }
        );
    }
  } catch (error: any) {
    console.error('Image optimization error:', error);
    return NextResponse.json(
      { error: 'Image optimization failed', details: error.message },
      { status: 500 }
    );
  }
}
