import axios from 'axios';
import bodyParser from 'body-parser';
import { Route, Server, LocalStorage } from '../../../class';
// import acknowledgements from '../../../configs/acknowledgements.json';

export default class Internal extends Route {
  public timeout: Set<string>;

  public acceptedOffers: LocalStorage;

  constructor(server: Server) {
    super(server);
    this.timeout = new Set();
    this.conf = {
      path: '/int',
    };
    this.acceptedOffers = new LocalStorage('accepted-offers');
  }

  public bind() {
    this.router.get('/directory', async (req, res) => {
      try {
        res.setHeader('Access-Control-Allow-Origin', '*');
        if (req.query.id) {
          let member = this.server.client.guilds.get(this.server.client.config.guildID).members.get(req.query.id.toString());
          if (!member) member = await this.server.client.getRESTGuildMember(this.server.client.config.guildID, req.query.id.toString());
          if (!member) return res.status(404).json({ code: this.constants.codes.NOT_FOUND, message: this.constants.messages.NOT_FOUND });
          const pagerNumber = await this.server.client.db.PagerNumber.findOne({ individualAssignID: member.id }).lean().exec();
          let status = false;
          if (member.roles.includes('446104438969466890') || member.roles.includes('701481967149121627')) status = true;
          return res.status(200).json({ staff: status, username: member.user.username, discriminator: member.user.discriminator, nick: member.nick, avatarURL: member.user.avatarURL, pager: pagerNumber?.num });
        }
        const acknowledgements = await this.server.client.db.Staff.find().lean().exec();
        return res.status(200).json(acknowledgements);
      } catch (err) {
        return this.handleError(err, res);
      }
    });

    this.router.get('/offer', async (_req, res) => {
      try {
        return res.status(410).json({ code: this.constants.codes.DEPRECATED, message: this.constants.codes.DEPRECATED });
      } catch (err) {
        return this.handleError(err, res);
      }
    });

    this.router.get('/score', async (_req, res) => {
      try {
        return res.status(410).json({ code: this.constants.codes.DEPRECATED, message: this.constants.codes.DEPRECATED });
      } catch (err) {
        return this.handleError(err, res);
      }
    });

    this.router.get('/id', async (req, res) => {
      try {
        if (req.query?.auth?.toString() !== this.server.client.config.internalKey) return res.status(401).json({ code: this.constants.codes.UNAUTHORIZED, message: this.constants.messages.UNAUTHORIZED });
        if (!req.query.pin) return res.status(400).json({ code: this.constants.codes.CLIENT_ERROR });
        const args = req.query.pin.toString();
        const user = await this.server.client.db.Score.findOne({ pin: [Number(args.split('-')[0]), Number(args.split('-')[1]), Number(args.split('-')[2])] }).lean().exec();
        if (!user) return res.status(404).json({ code: this.constants.codes.ACCOUNT_NOT_FOUND, message: this.constants.messages.NOT_FOUND });
        return res.status(200).json({ userID: user.userID });
      } catch (err) {
        return this.handleError(err, res);
      }
    });

    this.router.get('/pin', async (req, res) => {
      try {
        if (req.query?.auth?.toString() !== this.server.client.config.internalKey) return res.status(401).json({ code: this.constants.codes.UNAUTHORIZED, message: this.constants.messages.UNAUTHORIZED });
        if (!req.query.id) return res.status(400).json({ code: this.constants.codes.CLIENT_ERROR });

        const report = await this.server.client.db.Score.findOne({ userID: req.query.id.toString() });
        if (!report) return res.status(404).json({ code: this.constants.codes.ACCOUNT_NOT_FOUND, message: this.constants.messages.NOT_FOUND });
        return res.status(200).json({ pin: report.pin });
      } catch (err) {
        return this.handleError(err, res);
      }
    });

    this.router.post('/sub', bodyParser.raw({ type: 'application/json' }), async (req, res) => {
      try {
        const event = this.server.client.stripe.webhooks.constructEvent(req.body, req.headers['stripe-signature'], this.server.client.config.stripeSubSigningSecret);
        const data = <any> event.data.object;

        switch (event.type) {
          default:
            return res.sendStatus(400);
          case 'customer.subscription.created':
            if (data.items.data[0].price.product === 'prod_Hi4EYmf2am5VZt') {
              const customer = await this.server.client.db.Customer.findOne({ cusID: data.customer }).lean().exec();
              if (!customer) return res.sendStatus(404);
              await axios({
                method: 'get',
                url: `https://api.cloud.libraryofcode.org/wh/t3?userID=${customer.userID}&auth=${this.server.client.config.internalKey}`,
              });
              res.sendStatus(200);
            }
            break;
          case 'customer.subscription.deleted':
            if (data.items.data[0].price.product === 'prod_Hi4EYmf2am5VZt') {
              const customer = await this.server.client.db.Customer.findOne({ cusID: data.customer }).lean().exec();
              if (!customer) return res.sendStatus(404);
              await axios({
                method: 'get',
                url: `https://api.cloud.libraryofcode.org/wh/t3-rm?userID=${customer.userID}&auth=${this.server.client.config.internalKey}`,
              });
              return res.sendStatus(200);
            }
            break;
        }
        return null;
      } catch (err) {
        return this.handleError(err, res);
      }
    });
  }
}
