import { Request, Response, NextFunction } from "express";
import Stacker from "../middlewares/stacker.js";
import { GetClientAuthMiddleware } from "../middlewares/client.js";
import { UserMiddleware } from "../middlewares/user.js";
import RequestError, { HttpStatusCode } from "../../helper/request_error.js";
import ClientCode from "../../models/client_code.js";
import moment = require("moment");
import { randomBytes } from "crypto";
export const OAuthInternalApp = Stacker(
   GetClientAuthMiddleware(false, true),
   UserMiddleware,
   async (req: Request, res: Response) => {
      let { redirect_uri, state } = req.query as { [key: string]: string };
      if (!redirect_uri) {
         throw new RequestError(
            "No redirect url set!",
            HttpStatusCode.BAD_REQUEST
         );
      }

      let redurl = new URL(redirect_uri);

      let code = ClientCode.new({
         user: req.user._id,
         client: req.client._id,
         validTill: moment().add(30, "minutes").toDate(),
         code: randomBytes(16).toString("hex"),
         permissions: [],
      });
      await ClientCode.save(code);

      redurl.searchParams.set("code", code.code);
      if (state)
         redurl.searchParams.set("state", state);

      res.redirect(redurl.href);
      res.end();
   }
);
