import { checkUser, createLoginController } from "@/contexts/auth";
import Express, * as express from "express";
import passport from "passport";

interface AuthenticatedRequest extends Express.Request {
  logout(options: passport.LogOutOptions, done: (err: any) => void): void;
  logout(done: (err: any) => void): void;
}

export const authRouter = (appRouter: express.Router) => {
  const authRoutes: express.Router = express.Router({ mergeParams: true });

  //appRouter.use(registerMiddleware("isUser", isUser));
  //appRouter.use(registerMiddleware("isAdmin", isAdmin));

  authRoutes.post(
    "/login",
    passport.authenticate("local-email", { session: false }),
    (req: express.Request, res: express.Response, next: express.NextFunction) =>
      createLoginController(res.locals["context"]).execute(req, res, next)
  );

  authRoutes.post("/logout", checkUser, (req: express.Request, res: express.Response) => {
    const _req = req as AuthenticatedRequest;
    _req.logout(function (err) {
      if (err) {
        return res.status(500).json();
      }
      return res.status(200).json();
    });
  });

  authRoutes.post("/register");

  /*
    -> Sustituido por /profile
  
  authRoutes.get(
    "/identity",
    checkUser,
    (req: Express.Request, res: Express.Response, next: Express.NextFunction) =>
      createIdentityController(res.locals["context"]).execute(req, res, next)
  );*/

  appRouter.use("/auth", authRoutes);
};
