import { Format } from "@hibas123/logging";
import Logging from "@hibas123/nodelogging";
import { Server, } from "@hibas123/openauth-internalapi";
import { RequestObject, ResponseObject } from "@hibas123/openauth-internalapi/lib/service_base.js";
import { Request, Response } from "express";
import Stacker from "../middlewares/stacker.js";
import AccountService from "./services/account.js";
import LoginService from "./services/login.js";
import SecurityService from "./services/security.js";
import TFAService from "./services/twofactor.js";

export type SessionContext = Request;

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

const JRPCEndpoint = Stacker(
   async (req: Request, res: Response) => {
      let jrpcreq = req.body as RequestObject;
      let startTime = process.hrtime.bigint();
      const session = provider.getSession((data: ResponseObject) => {
         let time = process.hrtime.bigint() - startTime;
         let state = data.error ? Format.red(`err(${data.error.message})`) : Format.green("OK");

         Logging.getChild("JRPC").log(jrpcreq.method, state, "-", (Number(time / 10000n) / 100) + "ms");

         res.json(data);
      }, req);


      session.onMessage(jrpcreq);
   }
);

export default JRPCEndpoint;
