import type { NextFunction, Request, Response } from 'express'
import multer from 'multer'

import { getMaxUploadSizeBytes } from '../services/file-storage/file-storage-service.js'
import { createHttpError, sendRouteError } from '../utils/http.js'

const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: getMaxUploadSizeBytes(),
    files: 1,
  },
})

export function uploadSingleFile(req: Request, res: Response, next: NextFunction): void {
  upload.single('file')(req, res, (error: unknown) => {
    if (!error) {
      next()
      return
    }

    const normalizedError =
      error instanceof multer.MulterError && error.code === 'LIMIT_FILE_SIZE'
        ? createHttpError('文件超过上传大小限制', {
            statusCode: 400,
            errorCode: 'upload_file_too_large',
            cause: error,
          })
        : createHttpError('文件上传失败', {
            statusCode: 400,
            errorCode: 'upload_file_invalid',
            cause: error,
          })
    sendRouteError(res, normalizedError, '文件上传失败', '[files/upload]')
  })
}
