import { checkAdminOrSelf, checkIsAdmin } from "@/contexts/auth";
import { NextFunction, Request, Response, Router } from "express";
import {
  createCreateUserController,
  createDeleteUserController,
  createGetUserController,
  createListUsersController,
  createUpdateUserController,
} from "../../../../contexts/users/infrastructure/express/controllers";

export const usersRouter = (appRouter: Router) => {
  const userRoutes: Router = Router({ mergeParams: true });

  userRoutes.get("/", checkIsAdmin, (req: Request, res: Response, next: NextFunction) =>
    createListUsersController(res.locals["context"]).execute(req, res, next)
  );

  userRoutes.get("/:userId", checkAdminOrSelf, (req: Request, res: Response, next: NextFunction) =>
    createGetUserController(res.locals["context"]).execute(req, res, next)
  );

  userRoutes.post("/", checkIsAdmin, (req: Request, res: Response, next: NextFunction) =>
    createCreateUserController(res.locals["context"]).execute(req, res, next)
  );

  userRoutes.put("/:userId", checkIsAdmin, (req: Request, res: Response, next: NextFunction) =>
    createUpdateUserController(res.locals["context"]).execute(req, res, next)
  );

  userRoutes.delete("/:userId", checkIsAdmin, (req: Request, res: Response, next: NextFunction) =>
    createDeleteUserController(res.locals["context"]).execute(req, res, next)
  );

  appRouter.use("/users", userRoutes);
};
