/*
 * Copyright (C) 2019-2022 Open StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Api} from '@openstapps/gitlab-api';
import {Logger, AddLogLevel, Colorize} from '@openstapps/logger';
import {Command} from 'commander';
import {existsSync, readFileSync} from 'fs';
import path from 'path';
import {cwd, stdout} from 'process';
import {GITLAB_API_URL} from './configuration.js';
import {getUsedVersionMajorMinor} from './tasks/get-used-version.js';
import {remind} from './tasks/remind.js';
import {tidy} from './tasks/tidy.js';
import {removeLabel} from './tasks/remove-label.js';

// add default handler for unhandled rejections
process.on('unhandledRejection', async reason => {
  await (reason instanceof Error
    ? Logger.error('Unhandled rejection', reason.stack)
    : Logger.error('Unhandled rejection', reason));

  process.exit(1);
});

// instantiate new commander
const commander = new Command('openstapps-projectmanagement');

// error on unknown commands
commander.on('command:*', async () => {
  await Logger.error(
    'Invalid command: %s\nSee --help for a list of available commands.',
    commander.args.join(' '),
  );

  process.exit(1);
});

const gitlabApi = new Api(GITLAB_API_URL, process.env.GITLAB_PRIVATE_TOKEN as string);

Logger.setTransformations([new AddLogLevel(), new Colorize()]);

// eslint-disable-next-line unicorn/prefer-module
if (existsSync(path.join(__dirname, 'package.json'))) {
  // eslint-disable-next-line unicorn/prefer-module
  commander.version(JSON.parse(readFileSync(path.join(__dirname, '..', 'package.json')).toString()).version);
}

commander.command('unlabel').action(async () => {
  await removeLabel(gitlabApi);
  Logger.ok('Done!');
});

commander.command('tidy').action(async () => {
  await tidy(gitlabApi);
  Logger.ok('Done!');
});

commander.command('remind').action(async () => {
  await remind(gitlabApi);
  Logger.ok('Done!');
});

commander.command('get-used-version <dependency> [path]').action(async (dependency, filePath) => {
  let fallbackPath = cwd();
  if (typeof filePath === 'string' && filePath.length > 0) {
    fallbackPath = path.resolve(filePath);
  }

  stdout.write(await getUsedVersionMajorMinor(fallbackPath, dependency));
});

commander.parse(process.argv);
