const express = require("express");
const router = express.Router();
const logger = require("../utils/logger");
const path = require('path');
const fs = require('fs');

router.get("/:fileName", async (req, res) => {
  const fileName = req.params.fileName;

  if (!fileName) {
    logger.log("error", "fileName is undefined");

    return res.status(400).send("fileName is required");
  }

  const fileDir = path.resolve(process.cwd(), 'public', 'documents');
  const filePath = path.resolve(fileDir, fileName);

  try {
    await fs.promises.access(filePath, fs.constants.R_OK);

    res.download(filePath, fileName);
  } catch (error) {
    logger.log("error", error);

    res.status(500).send({ error: `Erreur pendant le téléchargement du fichier: ${error.message}` });
  }
});

module.exports = router;