// 585600289747369987
import { Member } from 'eris';
import { Client, Event } from '../class';
import { CloudServicesUtil } from '../util';

export default class GuildMemberUpdate extends Event {
  public client: Client;

  constructor(client: Client) {
    super(client);
    this.event = 'guildMemberUpdate';
  }

  public async run(_, member: Member, oldMember: { roles: string[], premiumSince: number }) {
    try {
      if (member.roles.includes('585600289747369987') && !oldMember.roles.includes('585600289747369987')) {
        const csAccountData = await CloudServicesUtil.fetchAccountStatus(member.id, this.client.config.internalKey);
        if (csAccountData.tier > 1) return;

        const status = await CloudServicesUtil.upgradeT2(member.id, this.client.config.internalKey);
        if (status !== 200) return;
      }

      if (!member.roles.includes('585600289747369987') && oldMember.roles.includes('585600289747369987')) {
        const csAccountData = await CloudServicesUtil.fetchAccountStatus(member.id, this.client.config.internalKey);
        if (csAccountData.tier === 1) return;

        const status = await CloudServicesUtil.downgradeT2(member.id, this.client.config.internalKey);
        if (status !== 200) return;
      }
    } catch (err) {
      this.client.util.handleError(err);
    }
  }
}

