import sharp from 'sharp';
import { HttpError } from './errors.js';

const MAX_OUTPUT_DIMENSION = Number.parseInt(process.env.MAX_IMAGE_DIMENSION || '1600', 10);
const WEBP_QUALITY = Number.parseInt(process.env.WEBP_QUALITY || '85', 10);

export async function normalizeToWebp(buffer) {
  let image;
  try {
    image = sharp(buffer, {
      animated: false,
      limitInputPixels: 20_000_000
    });
  } catch {
    throw new HttpError(400, 'Image could not be decoded.');
  }

  const metadata = await image.metadata().catch(() => null);
  if (!metadata?.width || !metadata?.height) {
    throw new HttpError(400, 'Image could not be decoded.');
  }
  const output = await image
    .rotate()
    .resize({
      width: MAX_OUTPUT_DIMENSION,
      height: MAX_OUTPUT_DIMENSION,
      fit: 'inside',
      withoutEnlargement: true
    })
    .webp({
      quality: WEBP_QUALITY,
      effort: 4
    })
    .toBuffer({ resolveWithObject: true });

  return {
    buffer: output.data,
    image: {
      format: 'webp',
      ext: 'webp',
      mime: 'image/webp',
      width: output.info.width,
      height: output.info.height,
      byteSize: output.data.length
    }
  };
}
