import { NextResponse } from 'next/server';
import { writeFile, mkdir } from 'fs/promises';
import path from 'path';
import { Buffer } from 'buffer';

export async function POST(req: Request) {
  try {
    const formData = await req.formData();
    const files = formData.getAll('file') as File[];

    if (!files || files.length === 0) {
      return NextResponse.json({ error: 'No files received.' }, { status: 400 });
    }

    // Limit total files if needed, but requirements say max 50 photos.
    if (files.length > 50) {
      return NextResponse.json({ error: 'Maximum 50 files allowed per upload.' }, { status: 400 });
    }

    const savedPaths: string[] = [];
    const uploadDir = path.join((process as any).cwd(), 'public/uploads');

    // Ensure upload directory exists
    try {
      await mkdir(uploadDir, { recursive: true });
    } catch (e) {
      // Ignore if directory exists
    }

    // Import sharp dynamically or at top level (assuming installed)
    const sharp = require('sharp'); // CommonJS import for simplicity, or use dynamic import if needed for ESM consistency
    const crypto = require('crypto');

    for (const file of files) {
      if (file.size > 5 * 1024 * 1024) {
        return NextResponse.json({ error: `File "${file.name}" exceeds the 5MB size limit.` }, { status: 400 });
      }

      const validTypes = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
      if (!validTypes.includes(file.type)) {
        return NextResponse.json({ error: `File "${file.name}" has an invalid format.` }, { status: 400 });
      }

      const buffer = Buffer.from(await file.arrayBuffer());
      const fileExt = path.extname(file.name).toLowerCase();
      // Safe extension check
      const safeExt = ['.jpg', '.jpeg', '.png', '.webp'].includes(fileExt) ? fileExt : '.jpg';
      const filename = `${crypto.randomUUID()}${safeExt}`;
      const filepath = path.join(uploadDir, filename);

      const imagePipeline = sharp(buffer)
        .resize(1920, 1920, { fit: 'inside', withoutEnlargement: true });

      if (safeExt === '.png') {
        await imagePipeline.png({ quality: 80, compressionLevel: 8 }).toFile(filepath);
      } else if (safeExt === '.webp') {
        await imagePipeline.webp({ quality: 80 }).toFile(filepath);
      } else {
        await imagePipeline.jpeg({ quality: 80, mozjpeg: true }).toFile(filepath);
      }

      savedPaths.push(`/uploads/${filename}`);
    }

    // Success response
    return NextResponse.json({
      success: true,
      filepath: savedPaths[0],
      filepaths: savedPaths
    });

  } catch (error: any) {
    console.error("Upload error:", error);
    return NextResponse.json({ error: 'Server error during upload: ' + error.message }, { status: 500 });
  }
}
