#!/usr/bin/env node

const yargs = require('yargs');
const { hideBin } = require('yargs/helpers');
const tools = require('./tools');

const globalOptions = {
  host_url: {
    describe: 'Coolify API host URL',
    type: 'string',
    demandOption: true
  },
  token: {
    describe: 'Coolify API token',
    type: 'string',
    demandOption: true
  }
};

const argv = yargs(hideBin(process.argv))
  .command('health', 'Check Coolify API health', y => y.options(globalOptions), async argv => {
    const result = await tools.health(argv.host_url, argv.token);
    console.log(result);
  })
  .command('version', 'Get Coolify version', y => y.options(globalOptions), async argv => {
    const result = await tools.version(argv.host_url, argv.token);
    console.log(result);
  })
  .command('apps', 'Manage applications', y =>
    y
      .command('list', 'List all applications', y2 => y2.options(globalOptions), async argv => {
        const result = await tools.listApps(argv.host_url, argv.token);
        console.log(result);
      })
      .command('start <id>', 'Start an application', y2 => y2.options(globalOptions).positional('id', { describe: 'Application ID', type: 'string' }), async argv => {
        const result = await tools.startApp(argv.host_url, argv.token, argv.id);
        console.log(result);
      })
      .command('stop <id>', 'Stop an application', y2 => y2.options(globalOptions).positional('id', { describe: 'Application ID', type: 'string' }), async argv => {
        const result = await tools.stopApp(argv.host_url, argv.token, argv.id);
        console.log(result);
      })
      .demandCommand(1, 'You need a subcommand for apps')
  )
  .demandCommand(1, 'You need a command')
  .help()
  .argv;
