import { Router } from "express";
import { createQueueTrackFromLibrary, findPermanentTrack } from "../storage/storageManager.js";

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

  router.get("/", (req, res) => {
    res.json(queue.snapshot());
  });

  router.post("/", (req, res) => {
    const { libraryTrackId, requestedBy } = req.body;

    if (!libraryTrackId) {
      return res.status(400).json({ error: "libraryTrackId manquant" });
    }

    const libraryTrack = findPermanentTrack(libraryTrackId);

    if (!libraryTrack) {
      return res.status(404).json({ error: "Fichier permanent introuvable" });
    }

    const track = createQueueTrackFromLibrary(libraryTrack, requestedBy);
    queue.enqueue(track);
    res.status(201).json({ track });
  });

  router.delete("/:trackId", async (req, res) => {
    const removed = await queue.remove(req.params.trackId);
    if (!removed) {
      return res.status(404).json({ error: "Piste introuvable" });
    }

    res.json({ removed });
  });

  router.patch("/:trackId/move", (req, res) => {
    const position = Number(req.body?.position);
    if (Number.isNaN(position)) {
      return res.status(400).json({ error: "position doit être un nombre" });
    }

    const snapshot = queue.move(req.params.trackId, position);

    if (!snapshot) {
      return res.status(404).json({ error: "Piste introuvable" });
    }

    res.json(snapshot);
  });

  return router;
}

export { queueRouter };
