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