import { Request, Response } from "express";
import promiseMiddleware from "../../helper/promiseMiddleware.js";
import RequestError, { HttpStatusCode } from "../../helper/request_error.js";
import RefreshToken from "../../models/refresh_token.js";
import User from "../../models/user.js";
import Client from "../../models/client.js";
import { getAccessTokenJWT } from "../../helper/jwt.js";

const JWTRoute = promiseMiddleware(async (req: Request, res: Response) => {
   let { refreshtoken } = req.query as { [key: string]: string };
   if (!refreshtoken)
      throw new RequestError(
         req.__("Refresh token not set"),
         HttpStatusCode.BAD_REQUEST
      );

   let token = await RefreshToken.findOne({ token: refreshtoken });
   if (!token)
      throw new RequestError(
         req.__("Invalid token"),
         HttpStatusCode.BAD_REQUEST
      );

   let user = await User.findById(token.user);
   if (!user) {
      token.valid = false;
      await RefreshToken.save(token);
      throw new RequestError(
         req.__("Invalid token"),
         HttpStatusCode.BAD_REQUEST
      );
   }

   let client = await Client.findById(token.client);

   let jwt = await getAccessTokenJWT({
      user,
      permissions: token.permissions,
      client,
   });
   res.json({ token: jwt });
});
export default JWTRoute;
