#!/usr/bin/env node
process.env.NODE_ENV = 'test'

const { resolve } = require('path')
const { cpus } = require('os')

const spawnAsync = require('@expo/spawn-async')
const ORA = require('ora')
const pLimit = require('p-limit')

const fixtures = [
  'children',
  'custom-dirs',
  'debug',
  'deprecate',
  'dynamic-routes',
  'empty',
  'error',
  'module',
  'ssr',
  'with-config',

  // csr,
  // dev,
  // generate,
  // fail generate,
  // fallback generate,
  // ssr,
  // ssr csp,
  // spa
  'basic'
]

const spinner = new ORA({ enabled: true })
const nuxtBuild = resolve(__dirname, '../bin/nuxt-build')

let _total = fixtures.length
let _done = 0
let remaining = () => ` (${_done}/${_total})`

async function buildFixture(name) {
  _done++

  let _name = `'${name}'`

  spinner.info('Building ' + _name + remaining())

  const rootDir = resolve(__dirname, '../test/fixtures', name)

  await spawnAsync('node', [nuxtBuild, rootDir])
    .catch((err) => {
      spinner.warn('Errors while building ' + _name + ': ' + err)
    })
    .then(() => {
      spinner.succeed('Built fixture: ' + _name + remaining())
    })
}

async function run() {
  const concurrency = Math.min(4, cpus().length)

  spinner.info('Building with concurrency of ' + concurrency)
  const limit = pLimit(concurrency)

  await Promise.all(fixtures.map(fixture =>
    limit(() => buildFixture(fixture))))
}

run()
  .catch(console.error) // eslint-disable-line no-console
  .then(() => process.exit(0))