# Author: VTEX
# To add more host patterns, create a new private method and add it to the
# strategies array

_ = require 'underscore'

class CheckHosts
  constructor: (options = {}) ->
    @options = options
    @strategies = [
      classicHost,
      vtexIoHost,
    ]

  ########################
  # Handler              #
  ########################

  handler: (req, res, next) =>
    @options.logger?.debug('CheckHosts middleware')
    return next() if req.url.indexOf('/meta/whoami') is 0

    cleanUrl = req.headers.host.replace(/^www\./i, '')

    # Iterates strategies to check which one matches the host
    resultsMap = _.map @strategies, (strategy) -> strategy(cleanUrl)
    match = _.find resultsMap, (result) -> result?.length

    req.vtex or= {}
    req.vtex.hostParts = match

    next()

  #######################
  # Private functions   #
  #######################

  # Checks for classic acount.vtexcommercestable.com.br host style
  classicHost = (url) ->
    envRegex = /(.*)\.vtex(commerce|commercebeta|commercealfa|commercestable|local|payments|lab|)\.com(\.br|)/
    envRegex.exec(url)

  # Checks for VTEX IO myvtex host style
  vtexIoHost = (url) ->
    envRegex = /(.*)\.myvtex\.com/
    match = envRegex.exec(url)
    match?.push('stable') # Add hostParts[2] with environment info
    return match

module.exports = CheckHosts
