import sharp from 'sharp';

// A photo-processing boundary, not an HTTP server. Cap request bodies at the proxy too.
export async function resizeUpload(chunks) {
  const buffers = [];
  let bytes = 0;
  for await (const chunk of chunks) {
    const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
    bytes += buffer.length;
    if (bytes > 5_000_000) throw new Error('Upload exceeds 5 MB');
    buffers.push(buffer);
  }
  if (bytes === 0) throw new Error('Empty upload');
  const input = Buffer.concat(buffers);
  const options = { limitInputPixels: 16_000_000, limitInputChannels: 4, failOn: 'warning' };
  const metadata = await sharp(input, options).metadata();
  if (!['jpeg', 'webp'].includes(metadata.format)) throw new Error('Upload a JPEG or WebP photo');
  if ((metadata.pages ?? 1) !== 1) throw new Error('Animated images are not accepted');
  return sharp(input, options).autoOrient().resize({ width: 1600, withoutEnlargement: true })
    .webp({ quality: 80 }).timeout({ seconds: 5 }).toBuffer();
}
