import createError from 'http-errors'
import path from 'path'
import { logger } from '../logger.js'

export default [function (req, res, next) {
  const { body, headers } = res
  if (!body) return next(createError(404, 'File does not exist.'))

  res.type(headers?.['content-type'] || path.extname(req.path) || 'html')
  if (headers) res.set(headers)

  res.status(200).send(body)
}, function (err, req, res, next) {
  if (!err) next()
  if (err.status >= 400 && err.status < 500) logger.warn(err)
  else logger.error(err)
  res.status(err.status || 500).send(err.message || 'Internal server error occured')
}]