import { Router } from "express";
import YubiKeyRoute from "./yubikey";
import { GetUserMiddleware } from "../../middlewares/user";
import Stacker from "../../middlewares/stacker";
import TwoFactor from "../../../models/twofactor";
import * as moment from "moment";
import RequestError, { HttpStatusCode } from "../../../helper/request_error";
import OTCRoute from "./otc";
import BackupCodeRoute from "./backup";

const TwoFactorRouter = Router();

TwoFactorRouter.get(
   "/",
   Stacker(GetUserMiddleware(true, true), async (req, res) => {
      let twofactor = await TwoFactor.find({ user: req.user._id, valid: true });
      let expired = twofactor.filter((e) =>
         e.expires ? moment().isAfter(moment(e.expires)) : false
      );
      await Promise.all(
         expired.map((e) => {
            e.valid = false;
            return TwoFactor.save(e);
         })
      );
      twofactor = twofactor.filter((e) => e.valid);
      let tfa = twofactor.map((e) => {
         return {
            id: e._id,
            name: e.name,
            type: e.type,
         };
      });
      res.json({ methods: tfa });
   })
);

TwoFactorRouter.delete(
   "/:id",
   Stacker(GetUserMiddleware(true, true), async (req, res) => {
      let { id } = req.params;
      let tfa = await TwoFactor.findById(id);
      if (!tfa || !tfa.user.equals(req.user._id)) {
         throw new RequestError("Invalid id", HttpStatusCode.BAD_REQUEST);
      }
      tfa.valid = false;
      await TwoFactor.save(tfa);
      res.json({ success: true });
   })
);

TwoFactorRouter.use("/yubikey", YubiKeyRoute);
TwoFactorRouter.use("/otc", OTCRoute);
TwoFactorRouter.use("/backup", BackupCodeRoute);

export default TwoFactorRouter;
