const { authJwt } = require("../middlewares");
const uploadPhysicalFile = require("../middlewares/upload_physical");

module.exports = (app) => {
  const templates = require("../controllers/template-file.controller.js");
  const router = require("express").Router();

  const handleUploadMiddleware = (req, res, next) => {
    uploadPhysicalFile(req, res, (err) => {
      if (err) {
        return res.status(500).send({
          message: `Upload Error: ${err.message || err}`,
        });
      }
      return next();
    });
  };

  router.get("/", [authJwt.verifyToken], templates.listTemplates);
  router.post(
    "/:key/upload",
    [authJwt.verifyToken],
    templates.prepareUploadContext,
    handleUploadMiddleware,
    templates.uploadTemplate
  );

  app.use("/api/template-files", router);
};
