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

export default class AddRedirect extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'addredirect';
    this.description = 'Adds a redirect link for \'loc.sh\'';
    this.usage = `${this.client.config.prefix}addredirect <redirect to url> <key>`;
    this.aliases = ['ar'];
    this.permissions = 6;
    this.enabled = true;
  }

  public async run(message: Message, args: string[]) {
    try {
      if (!args[0]) return this.client.commands.get('help').run(message, [this.name]);
      const check = await this.client.db.Redirect.findOne({ key: args[1].toLowerCase() });
      if (check) return this.error(message.channel, `Redirect key ${args[1].toLowerCase()} already exists. Linked to: ${check.to}`);
      try {
        const test = new URL(args[0]);
        if (test.protocol !== 'https:') return this.error(message.channel, 'Protocol must be HTTPS.');
      } catch {
        return this.error(message.channel, 'This doesn\'t appear to be a valid URL.');
      }
      if ((/^[a-zA-Z0-9]+$/gi.test(args[1].toLowerCase().replace('-', '').trim()) === false) || args[1].toLowerCase().length > 15) return this.error(message.channel, 'Invalid key. The key must be alphanumeric and less than 16 characters.');
      const redirect = new this.client.db.Redirect({
        key: args[1].toLowerCase(),
        to: args[0],
        visitedCount: 0,
      });
      await redirect.save();
      return this.success(message.channel, `Redirect https://loc.sh/${args[1].toLowerCase()} -> ${args[0]} is now active.`);
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
