import { Injectable, PipeTransform } from '@nestjs/common';
import * as path from 'path';
import sharp from 'sharp';

@Injectable()
export class ImageProcessingPipe implements PipeTransform {
  async transform(
    files: Express.Multer.File[] | Express.Multer.File,
  ): Promise<Express.Multer.File[] | Express.Multer.File> {
    if (!files) return files;

    const processItem = async (
      file: Express.Multer.File,
    ): Promise<Express.Multer.File> => {
      const processedBuffer = await sharp(file.buffer)
        .webp({ quality: 80 })
        .toBuffer();

      const originalName = path.parse(file.originalname).name;

      return {
        ...file,
        buffer: processedBuffer,
        originalname: `${originalName}.webp`,
        mimetype: 'image/webp',
        size: processedBuffer.length,
      };
    };

    if (Array.isArray(files)) {
      return await Promise.all(files.map((file) => processItem(file)));
    }

    return await processItem(files);
  }
}
