const handlers = []

export const register = (method, urlPattern, handler) => {
  const paramNames = []
  const regexSource = urlPattern.replace(/:([A-Za-z][\dA-Za-z]*)/g, (_, name) => {
    paramNames.push(name)
    return '([^/]+)'
  })
  const regex = new RegExp(`^${regexSource}$`)
  handlers.push({ method: method.toUpperCase(), regex, paramNames, handler })
}

export const findHandler = (method, url) => {
  const upper = method.toUpperCase()
  for (const entry of handlers) {
    if (entry.method !== upper) continue
    const match = entry.regex.exec(url)
    if (match) {
      const params = {}
      entry.paramNames.forEach((name, i) => {
        params[name] = decodeURIComponent(match[i + 1])
      })
      return { entry, params }
    }
  }
  return null
}
