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

export default class X509_Upload extends Command {
  constructor(client: Client) {
    super(client);
    this.name = 'upload';
    this.aliases = ['add', 'link', 'connect'];
    this.description = 'Uploads your x509 PEM-encoded certificate as a file to our database for authenticity and identity verification.';
    this.usage = `${this.client.config.prefix}x509 ${this.name}`;
    this.permissions = 0;
    this.guildOnly = true;
    this.enabled = true;
  }

  public async run(message: Message) {
    if (!message.attachments.length) return this.error(message.channel, 'Please upload your x509 certificate as an attachment.');
    if (!await this.client.db.Member.exists({ userID: message.author.id })) {
      await this.client.db.Member.create({ userID: message.author.id });
    }
    const [x509Attachment] = message.attachments;
    const x509Req: AxiosResponse<string> = await axios(x509Attachment.proxy_url);
    const x509 = x509Req.data;
    try {
      await axios.post('https://certapi.libraryofcode.org/parse', x509);
    } catch {
      return this.error(message.channel, 'Unable to parse your x509 certificate.');
    } finally {
      await this.client.db.Member.updateOne({ userID: message.author.id }, { x509 });
      this.success(message.channel, 'x509 certificate successfully uploaded to your account.');
    }
  }
}
