import { fetchFileWithHeaders, loadFromCache, saveAsyncToCache } from '../files.js'
import { NotFoundError } from '../errors.js'
import createError from 'http-errors'

export default async function (req, res, next) {
  try {
    if (req.method !== 'GET') return next()
    const version = res.version
    let data = await loadFromCache({
      path: req.path,
      version
    })
    if (!data) {
      const path = req.path === '/' ? '/index.html' : req.path
      data = await saveAsyncToCache({ version, path, promise: fetchFileWithHeaders({ path, version }) })
    }

    const { body, headers, sha256Sum } = data
    res.set(headers)
    res.locals.sha256Sum = sha256Sum
    res.send(body)
  } catch (err) {
    const errors = err.errors || [err]
    const fileNotFound = errors.reduce((memo, error) => memo && error instanceof NotFoundError, true)
    if (fileNotFound) next(createError(404, 'File does not exist.'))
    else next(err)
  }
}