const proxy = require('express-http-proxy')

const use = true

// const gate = '10.180.88.84:8093'
// const gate = '10.180.88.71:6443'
const gate = process.env.VUE_APP_GATEWAY
const base_url = process.env.VUE_APP_BASE_API
const minioKey = process.env.VUE_APP_MINIO.replace(base_url, '')
const thumbnailKey = process.env.VUE_APP_THUMBNAIL.replace(base_url, '')

const isHttps = !/^[0-9.:]+$/.test(gate)

module.exports = {
  register (router) {
    if (use) {
      router.use('/auth', createProxy(process.env.VUE_APP_KEYCLOAK_OPTIONS_URL))
      router.use(minioKey, createProxy(gate, minioKey))
      router.use(thumbnailKey, createThumbnailProxy(gate))
      router.use('/', createProxy(gate, '/prod-api'))
    }
  }
}

function createProxy (to, replace) {
  return proxy(to, {
    https: isHttps,
    parseReqBody: false,
    proxyReqPathResolver (req) {
      const url = replace ? `${replace}${req.url}` : req.url
      console.log(`proxy ${url} to ${to}`)
      return url
    }
  })
}

function createThumbnailProxy (to) {
  return proxy(to, {
    https: isHttps,
    parseReqBody: false,
    proxyReqPathResolver (req) {
      const url = `${thumbnailKey}${req.url.replace(new RegExp(`http.*${minioKey}`), `http${isHttps ? 's' : ''}://${gate}${minioKey}`)}`
      console.log(`thumbnail ${url} to ${to}`)
      return url
    }
  })
}
