import { Request, Response } from "express";
import Stacker from "../middlewares/stacker";
import { GetUserMiddleware } from "../middlewares/user";
import LoginToken, { CheckToken } from "../../models/login_token";
import RequestError, { HttpStatusCode } from "../../helper/request_error";

export const GetToken = Stacker(
   GetUserMiddleware(true, true),
   async (req: Request, res: Response) => {
      let raw_token = await LoginToken.find({
         user: req.user._id,
         valid: true,
      });
      let token = await Promise.all(
         raw_token
            .map(async (token) => {
               await CheckToken(token);
               return {
                  id: token._id,
                  special: token.special,
                  ip: token.ip,
                  browser: token.browser,
                  isthis: token._id.equals(
                     token.special ? req.token.special._id : req.token.login._id
                  ),
               };
            })
            .filter((t) => t !== undefined)
      );
      res.json({ token });
   }
);

export const DeleteToken = Stacker(
   GetUserMiddleware(true, true),
   async (req: Request, res: Response) => {
      let { id } = req.params;
      let token = await LoginToken.findById(id);
      if (!token || !token.user.equals(req.user._id))
         throw new RequestError("Invalid ID", HttpStatusCode.BAD_REQUEST);
      token.valid = false;
      await LoginToken.save(token);
      res.json({ success: true });
   }
);
