import { Message, TextChannel } from 'eris';
import { apply as Apply } from '.';
import { Client, Command, RichEmbed } from '../class';

export default class SAA_Approve extends Command {
  public applyCommand: Apply;

  constructor(client: Client) {
    super(client);
    this.name = 'approve';
    this.description = 'Approves a Staff-assisted Application (SAA).';
    this.usage = `${this.client.config.prefix}saa approve <applicationID>`;
    this.permissions = 4;
    this.guildOnly = true;
    this.enabled = true;

    this.applyCommand = <Apply> this.client.commands.get('apply');
  }

  public async run(message: Message, args: string[]) {
    try {
      if (!args[0]) return this.client.commands.get('help').run(message, [this.name]);

      const saa = await this.client.db.SAA.findOne({ applicationID: args[0] }).lean().exec();
      if (!saa) return this.error(message.channel, 'Unable to locate SAA.');
      const member = this.client.util.resolveMember(saa.userID, this.mainGuild);
      if (!member) return this.error(message.channel, 'Unable to locate member.');
      const report = await this.client.db.Score.findOne({ userID: saa.userID }).lean().exec();
      if (!report) return this.error(message.channel, 'Unable to locate Community Report.');
      const staff = await this.client.db.Staff.findOne({ userID: message.author.id }).lean().exec();
      if (!staff) return this.error(message.channel, 'Unable to locate Staff information.');

      await this.applyCommand.services.get(saa.serviceCode).func(this.client, member.id);

      const embed = new RichEmbed();
      embed.setTitle('Staff Assisted Application - Decision');
      embed.setColor('#50c878');
      // eslint-disable-next-line no-useless-escape
      embed.addField('User', `${member.username}#${member.discriminator} | XXX-XX-${report.pin[2]}`);
      embed.addField('Decision', 'APPROVED');
      embed.addField('Underwriter', `${message.author.username}, ${staff.pn.slice(0, 2).join(', ')} *on behalf of Library of Code sp-us*`);
      embed.addField('Application ID', saa.applicationID);
      embed.addField('Service Code', saa.serviceCode);
      embed.setFooter(this.client.user.username, this.client.user.avatarURL);
      embed.setTimestamp();

      const log = <TextChannel> this.client.guilds.get(this.client.config.guildID).channels.get('611584771356622849');
      log.createMessage({ embed });

      embed.setDescription(`*A SAA has been ran in your name for a service, this embed contains the information about the result of that decision.*\n\nAccess link to the EDS recommendation for this decision: https://eds.libraryofcode.org/dec/${saa.edsToken}`);
      const chan = await this.client.getDMChannel(saa.userID);
      chan.createMessage({ embed }).then(() => this.success(message.channel, 'SAA successfully processed.')).catch(() => this.error(message.channel, 'Unable to deliver decision to user.'));

      await this.client.db.SAA.deleteOne({ _id: saa._id }).lean().exec();
    } catch (err) {
      return this.client.util.handleError(err, message, this);
    }
  }
}
