import { Request, Router } from "express";
import promiseMiddleware from "../../helper/promiseMiddleware.js";
import RegCode from "../../models/regcodes.js";
import { randomBytes } from "crypto";
import moment = require("moment");

const RegCodeRoute: Router = Router();
RegCodeRoute.route("/")
   /**
    * @api {get} /admin/regcode
    * @apiName AdminGetRegcodes
    *
    * @apiGroup admin_regcode
    * @apiPermission admin
    *
    * @apiSuccess {Object[]} regcodes
    * @apiSuccess {String} permissions._id The ID
    * @apiSuccess {String} permissions.token The Regcode Token
    * @apiSuccess {String} permissions.valid Defines if the Regcode is valid
    * @apiSuccess {String} permissions.validTill Expiration date of RegCode
    */
   .get(
      promiseMiddleware(async (req, res) => {
         let regcodes = await RegCode.find({});
         res.json(regcodes);
      })
   )
   /**
    * @api {delete} /admin/regcode
    * @apiName AdminDeleteRegcode
    *
    * @apiParam {String} id The id of the RegCode
    *
    * @apiGroup admin_regcode
    * @apiPermission admin
    *
    * @apiSuccess {Boolean} success
    */
   .delete(
      promiseMiddleware(async (req, res) => {
         let { id } = req.query as { [key: string]: string };
         await RegCode.delete(id);
         res.json({ success: true });
      })
   )
   /**
    * @api {post} /admin/regcode
    * @apiName AdminAddRegcode
    *
    * @apiGroup admin_regcode
    * @apiPermission admin
    *
    * @apiSuccess {String} code The newly created code
    */
   .post(
      promiseMiddleware(async (req, res) => {
         let regcode = RegCode.new({
            token: randomBytes(10).toString("hex"),
            valid: true,
            validTill: moment().add("1", "month").toDate(),
         });
         await RegCode.save(regcode);
         res.json({ code: regcode.token });
      })
   );

export default RegCodeRoute;
