import multer from 'multer'
import { ValidationError } from '../errors'

const MAX_FILE_SIZE = 10 * 1024 * 1024 // 10 MB

/**
 * Shared multer instance used by all upload endpoints.
 * Files are kept in memory so services receive a Buffer — no temp-file cleanup needed.
 */
export const imageUpload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: MAX_FILE_SIZE },
})

/**
 * Asserts that a file was provided and is an image MIME type.
 * Call inside the route handler after the multer middleware runs.
 */
export function assertImageFile(
  file: Express.Multer.File | undefined,
  fieldLabel = 'file',
): asserts file is Express.Multer.File {
  if (!file) throw new ValidationError(`A ${fieldLabel} is required`)
  if (!file.mimetype.startsWith('image/')) throw new ValidationError('Only image uploads are supported')
}

/**
 * Asserts that at least one file was provided and all files are images.
 */
export function assertImageFiles(files: Express.Multer.File[], fieldLabel = 'photos'): void {
  if (!files || files.length === 0) throw new ValidationError(`At least one ${fieldLabel} file is required`)
  const nonImage = files.find((f) => !f.mimetype.startsWith('image/'))
  if (nonImage) throw new ValidationError(`All uploaded files must be images — "${nonImage.originalname}" is not`)
}
