import { Request, Response } from "express";
import Stacker from "../../middlewares/stacker.js";
import { GetUserMiddleware } from "../../middlewares/user.js";
import RequestError, { HttpStatusCode } from "../../../helper/request_error.js";
import { getClientWithOrigin } from "./_helper.js";
import Permission from "../../../models/permissions.js";

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 });
   }
);
