#!/usr/bin/env node

require('assert-node-version')()

const chalk = require('chalk').default
const fs = require('fs')
const path = require('path')
const JsonSchemaRefParser = require('json-schema-ref-parser')

const { readYaml, saveJson, suffixFilename } = require('../utils/utils')

const DIST_FOLDER = 'dist'

dereferenceAll()

async function dereferenceAll () {
  let hasError = false
  for (const apiFile of fs.readdirSync(DIST_FOLDER)) {
    if (apiFile.endsWith('.json')) {
      try {
        await dereference(path.join(DIST_FOLDER, apiFile))
      } catch (e) {
        hasError = true
        console.log(e)
      }
    }
  }

  if (hasError) {
    console.log(chalk.red('Dereferencing failed'))
    process.exit(1)
  }
}

/**
 * Derefernces OpenAPI file.
 *
 * @param {string} openapiFilename - Path to the OpenAPI definition file.
 */
async function dereference (openapiFilename) {
  let openapi = readYaml(openapiFilename)

  // fully dereference even internal $refs
  openapi = await JsonSchemaRefParser.dereference(openapi, {
    dereference: {
      circular: false
    }
  })
  // remove components as they are not used after full dereferencing
  delete openapi.components
  const outputFilename = suffixFilename(openapiFilename, '-deref')
  saveJson(outputFilename, openapi)
  console.log(`Dereferenced ${chalk.blue(outputFilename)}`)
}
