import { Request, Response } from "express";
import Stacker from "../middlewares/stacker";
import { GetUserMiddleware } from "../middlewares/user";
import { IUser } from "../../models/user";
import { Server } from "@hibas123/openauth-internalapi";
import AccountService from "./account_service";
import SecurityService from "./security_service";
import { ILoginToken } from "../../models/login_token";

export interface SessionContext {
   user: IUser,
   request: Request,
   isAdmin: boolean,
   special: boolean,
   token: {
      login: ILoginToken,
      special?: ILoginToken,
   }
}

const provider = new Server.ServiceProvider<SessionContext>();
provider.addService(new AccountService());
provider.addService(new SecurityService());

const JRPCEndpoint = Stacker(
   GetUserMiddleware(true, true),
   async (req: Request, res: Response) => {
      const session = provider.getSession((data) => {
         res.json(data);
      }, {
         user: req.user,
         request: req,
         isAdmin: req.isAdmin,
         special: req.special,
         token: {
            login: req.token.login,
            special: req.token.special,
         }
      });

      session.onMessage(req.body);
   }
);

export default JRPCEndpoint;
