import multer from 'multer';
import sharp from 'sharp';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { promises as fs } from 'fs';

const __dirname = dirname(fileURLToPath(import.meta.url));
const uploadsDir = join(__dirname, '../../uploads');

const storage = multer.memoryStorage();
const upload = multer({
  storage,
  limits: { fileSize: 10 * 1024 * 1024 }, // 10MB
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('Only image files allowed'));
    }
  }
});

export const processImage = async (file) => {
  const filename = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  const webpPath = join(uploadsDir, `${filename}.webp`);
  const jpgPath = join(uploadsDir, `${filename}.jpg`);

  try {
    const image = sharp(file.buffer);
    const metadata = await image.metadata();

    // Create optimized WebP version
    await image
      .resize(1200, 800, { fit: 'inside', withoutEnlargement: true })
      .webp({ quality: 80 })
      .toFile(webpPath);

    // Create optimized JPG fallback
    await sharp(file.buffer)
      .resize(1200, 800, { fit: 'inside', withoutEnlargement: true })
      .jpeg({ quality: 80 })
      .toFile(jpgPath);

    return {
      filename: `${filename}.webp`,
      jpgFilename: `${filename}.jpg`,
      width: metadata.width,
      height: metadata.height,
      size: file.size
    };
  } catch (err) {
    console.error('Image processing error:', err);
    throw err;
  }
};

export const uploadMiddleware = upload.single('image');
