import axios, { AxiosResponse } from 'axios';
import { Route, Server } from '../../../class';

import { X509Certificate } from '../../../commands/x509';
import { PGPKey, PublicKeyAlgorithm } from '../../../commands/pgp';

export default class Internal extends Route {
  constructor(server: Server) {
    super(server);
    this.conf = {
      path: '/internal',
    };
  }

  public bind() {
    this.router.all('*', (_req, res, next) => {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', '*');
      res.setHeader('Access-Control-Allow-Headers', '*');
      next();
    });

    this.router.get('/check-cwg-self-auth', async (req, res) => {
      if (req.query.internalKey !== this.server.client.config.internalKey) return res.sendStatus(401);

      const member = await this.server.client.guilds.get(this.server.client.config.guildID).getRESTMember(req.query.userID.toString());
      if (!member) return res.sendStatus(404);

      const tokenC = await this.server.client.db.redis.get(req.query.token.toString());
      if (!tokenC) return res.sendStatus(404);

      if (tokenC !== member.id) return res.sendStatus(403);

      await this.server.client.db.redis.del(req.query.token.toString());

      return res.sendStatus(204);
    });
  }
}
