import { Router } from "express";
import multer from "multer";
import { TEMP_DIR, registerUploadedFile } from "../storage/storageManager.js";

const upload = multer({
  dest: TEMP_DIR,
  limits: {
    fileSize: 150 * 1024 * 1024,
  },
});

function uploadsRouter({ queue }) {
  const router = Router();

  router.post("/", upload.single("file"), async (req, res, next) => {
    if (!req.file) {
      return res.status(400).json({ error: "Aucun fichier reçu" });
    }

    const permanent = req.body?.permanent === "true";
    const enqueue = req.body?.enqueue !== "false";
    const uploader = req.body?.uploader || "web-ui";

    try {
      const track = registerUploadedFile(req.file, { permanent, uploader });

      if (enqueue) {
        queue.enqueue(track);
      }

      return res.status(201).json({ track, enqueued: enqueue });
    } catch (error) {
      return next(error);
    }
  });

  return router;
}

export { uploadsRouter };
