import axios, { AxiosResponse } from 'axios';
import { Command, Client, CmdContext } 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(ctx: CmdContext) {
    if (!ctx.message.attachments.length) return this.error(ctx.message.channel, 'Please upload your x509 certificate as an attachment.');
    if (!await this.client.db.mongo.Member.exists({ userID: ctx.message.author.id })) {
      await this.client.db.mongo.Member.create({ userID: ctx.message.author.id });
    }
    const [x509Attachment] = ctx.message.attachments;
    const x509Req: AxiosResponse<string> = await axios(x509Attachment.url);
    const x509 = x509Req.data;
    try {
      await axios.post('https://certapi.libraryofcode.org/parse', x509);
    } catch {
      return this.error(ctx.message.channel, 'Unable to parse your x509 certificate.');
    }
    await this.client.db.mongo.Member.updateOne({ userID: ctx.message.author.id }, { x509 });
    this.success(ctx.message.channel, 'x509 certificate successfully uploaded to your account.');
  }
}
