const { basename } = require('path')
const semver = require('semver')
const jsonmergepatch = require('json-merge-patch')

const OVERLAYS_KEY = 'x-githubEnterpriseOverlays'

module.exports = class OverlaysMerger {
  static get rule () {
    return 'githubOverlaysMerger'
  }

  OpenAPIRoot () {
    return {
      onEnter: (_, _1, ctx) => {
        const name = basename(ctx.filePath, '.yml')
        this.version = name === 'api.github.com' ? 'public' : `${name.replace('ghe-', '')}.0`
      }
    }
  }

  any () {
    return {
      onEnter: node => {
        // we never patch public, only enterprise
        if (node[OVERLAYS_KEY] && this.version !== 'public') {
          for (const range of Object.keys(node[OVERLAYS_KEY])) {
            if (semver.satisfies(this.version, range)) {
              const overlay = node[OVERLAYS_KEY][range]

              if (overlay) {
                jsonmergepatch.apply(node, overlay)
              }

              // apply only first matched range
              break
            }
          }
        }
        delete node[OVERLAYS_KEY]
      }
    }
  }
}
