const getSchema = require('./get-schema')
const Operation = require('./operation')
const { chain } = require('lodash')

/*
In OpenAPI, each HTTP operation is nested within an object as combination of request path and HTTP verb:

 paths:
   /app: <-- path
     GET: ... <-- verb
     POST: ...

 To make operations easer to work with, this module takes an OpenAPI schema as input
 and flattens them into an array of Operation objects.
*/

module.exports = async function getOperations (schema) {
  if (!schema) schema = await getSchema()

  const operations = []

  for (const [requestPath, operationsAtPath] of Object.entries(schema.paths)) {
    for (const [verb, props] of Object.entries(operationsAtPath)) {
      const operation = new Operation(verb, requestPath, props)
      operations.push(operation)
    }
  }

  return chain(operations)
    .orderBy('operationId')
    .value()
}
