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

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

  router.get("/", (req, res) => {
    res.json({ tracks: getPermanentLibrary() });
  });

  router.delete("/:libraryId", (req, res) => {
    const track = deletePermanentTrack(req.params.libraryId);

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

    queue.removeByLibraryId(track.id);
    res.json({ removed: track });
  });

  router.post("/:libraryId/enqueue", (req, res) => {
    const baseTrack = findPermanentTrack(req.params.libraryId);
    if (!baseTrack) {
      return res.status(404).json({ error: "Fichier permanent introuvable" });
    }

    const queueTrack = createQueueTrackFromLibrary(
      baseTrack,
      req.body?.requestedBy
    );
    queue.enqueue(queueTrack);
    res.status(201).json({ track: queueTrack });
  });

  return router;
}

export { libraryRouter };
