import express from "express";
import path from "path";
import { config } from "../config.js";
import { authMiddleware } from "./middlewares/auth.js";
import { libraryRouter } from "./routes/library.js";
import { playerRouter } from "./routes/player.js";
import { queueRouter } from "./routes/queue.js";
import { uploadsRouter } from "./routes/uploads.js";
import { ensureStorageLayout } from "./storage/storageManager.js";

const PUBLIC_DIR = path.join(process.cwd(), "public");

function startWebServer(dependencies) {
  ensureStorageLayout();

  const app = express();
  app.use(express.json());

  const apiRouter = express.Router();
  apiRouter.use(authMiddleware);
  apiRouter.use("/uploads", uploadsRouter(dependencies));
  apiRouter.use("/queue", queueRouter(dependencies));
  apiRouter.use("/library", libraryRouter(dependencies));
  apiRouter.use("/player", playerRouter(dependencies));

  app.use("/api", apiRouter);
  app.get(["/jukebox", "/jukebox/"], (_req, res) =>
    res.sendFile(path.join(PUBLIC_DIR, "jukebox.html"))
  );
  app.use(express.static(PUBLIC_DIR));

  const port = Number(process.env.PORT || config.webServerPort || 3000);

  app.listen(port, () => {
    console.log(
      `[${new Date().toLocaleString()}] Web control server listening on port ${port}`
    );
  });

  return app;
}

export { startWebServer };
