const execa = require('execa')
const { clearConsole } = require('./util/clearConsole')
const shouldBackend = require('./util/shouldBackend')
const loadUserOptions = require('./loadUserOptions')
const { error, stopSpinner, log } = require('@vue/cli-shared-utils')

async function serve (options = {}, context = process.cwd()) {
  console.log(options)
  await clearConsole(true)

  const userOptions = await loadUserOptions(context)

  const isShouldBackend = await shouldBackend(userOptions.type)

  const frontendPath = isShouldBackend ? `${context}/frontend` : context

  console.log(`vue-cli-service serve ${options.hot ? '--hot' : ''}`)
  console.log(frontendPath)
  // run vue cli build
  log()
  execa('npm run serve ', { cwd: frontendPath })
}

module.exports = (...args) => {
  return serve(...args).catch(err => {
    stopSpinner(false) // do not persist
    error(err)
    if (!process.env.CONTROLLA_CLI_TEST) {
      process.exit(1)
    }
  })
}
