import { Request, Response } from "express";
import Stacker from "../../middlewares/stacker";
import { GetUserMiddleware } from "../../middlewares/user";
import { URL } from "url";
import Client from "../../../models/client";
import RequestError, { HttpStatusCode } from "../../../helper/request_error";
import { randomBytes } from "crypto";
import moment = require("moment");
import RefreshToken from "../../../models/refresh_token";
import { refreshTokenValidTime } from "../../../config";
import { getClientWithOrigin } from "./_helper";
import Permission from "../../../models/permissions";

export const GetPermissionsForAuthRequest = Stacker(
   GetUserMiddleware(true, false),
   async (req: Request, res: Response) => {
      const { client_id, origin, permissions } = req.query as {
         [key: string]: string;
      };

      const client = await getClientWithOrigin(client_id, origin);

      const perm = permissions.split(",").filter((e) => !!e);

      const resolved = await Promise.all(
         perm.map((p) => Permission.findById(p))
      );

      if (resolved.some((e) => e.grant_type !== "user")) {
         throw new RequestError(
            "Invalid Permission requested",
            HttpStatusCode.BAD_REQUEST
         );
      }

      res.json({ permissions: resolved });
   }
);
