import { Message } from 'eris';
import { randomBytes } from 'crypto';
import { Client, Command } from '../class';

export default class AddMerchant extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'addmerchant';
    this.description = 'Creates a new merchant.';
    this.usage = `${this.client.config.prefix}addmerchant <privileged: 1 for yes | 0 for no> <type: 0 for only soft | 1 for soft and hard> <merchant name>`;
    this.aliases = ['am'];
    this.permissions = 6;
    this.guildOnly = true;
    this.enabled = true;
  }

  public async run(message: Message, args: string[]) {
    try {
      if (!args[1]) return this.client.commands.get('help').run(message, [this.name]);
      if ((Number(args[0]) !== 0) && (Number(args[0]) !== 1)) return this.error(message.channel, 'Invalid permissions.');
      if ((Number(args[1]) !== 0) && (Number(args[1]) !== 1)) return this.error(message.channel, 'Invalid permissions.');
      const key = randomBytes(20).toString('hex');
      const merchant = await (new this.client.db.Merchant({
        name: args.slice(2).join(' '),
        privileged: Number(args[0]),
        type: Number(args[1]),
        key,
        pulls: [],
      })).save();
      return this.success(message.channel, `Created merchant (${merchant._id}). \`${args.slice(2).join(' ')}\`\n\n\`${key}\``);
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
