const { readProfile } = require('../../profile')
const { v4: uuidv4 } = require('uuid')
const { basename } = require('path')
const MultiProgress = require('multi-progress')
const { uploadWithProgress } = require('../../upload')
const { getErrorMessage } = require('../../error')
const { getAxios } = require('../../utils')

async function builder (yargs) {
  yargs.positional('files', {
    type: 'string',
    describe: 'One or more extension file paths',
    demandOption: true
  }).option('verbose', {
    alias: 'v',
    type: 'boolean',
    describe: 'Console will receive verbose error output'
  })
}

async function handler (argv) {
  const profile = readProfile()

  const multi = new MultiProgress(process.stderr)

  const files = argv.files

  await Promise.all(files.map(async (file) => {
    const fileName = basename(file)
    const imageId = uuidv4()
    const url = profile.endpoint +
      `/api/v1/domain/image-upload/extension/${imageId}/${encodeURIComponent(fileName)}`

    try {
      await uploadWithProgress(url, profile.token, file, multi)

      console.log(`Extension uploaded ${imageId}`)
      console.log('Loading extension...')
      const body = {
        imageId
      }
      const installUrl = profile.endpoint + '/api/v1/extensions'
      try {
        const axios = await getAxios()
        await axios.post(installUrl, body)
        console.log('Extension load complete')
      } catch (error) {
        const errorMessage = error.response && error.response.data
          ? error.response.data
          : error.message || error
        console.error(`Extension load failed: ${JSON.stringify(errorMessage)}`)
        if (argv.detailedErrors) {
          console.log(error)
        }
      }
    } catch (error) {
      const errorMessage = getErrorMessage(error)
      console.error(`Extension load failed: ${errorMessage}`)

      if (argv.detailedErrors) {
        console.log(error)
      }
    }
  }))
}

module.exports = {
  builder,
  handler,
  command: 'load <files..>',
  describe: 'Load domain extensions'
}
