import express from "express";
import cors from "cors";
import morgan from "morgan";
import path from "path";
import { fileURLToPath } from "url";
import { config } from "./config.js";
import { basicAuth } from "./auth/basicAuth.js";
import { notesRoutes } from "./notes/notes.routes.js";
import { initNotesStorage } from "./notes/notes.storage.js";
import { CleanupQueue } from "./queue/queue.js";
import { handleCleanupJob } from "./queue/cleanup.worker.js";
import { logInfo } from "./utils/logger.js";

const app = express();
app.use(cors());
app.use(express.json({ limit: "2mb" }));
app.use(morgan("dev"));

await initNotesStorage();

const cleanupQueue = new CleanupQueue(handleCleanupJob);
await cleanupQueue.load();
cleanupQueue.start();

const apiRouter = express.Router();
apiRouter.get("/health", (_req, res) => {
  res.json({ status: "ok" });
});
apiRouter.use(notesRoutes(cleanupQueue));

app.use("/api", basicAuth, apiRouter);

if (process.env.NODE_ENV === "production") {
  const __filename = fileURLToPath(import.meta.url);
  const __dirname = path.dirname(__filename);
  const publicDir = path.resolve(__dirname, "public");
  app.use(express.static(publicDir));
  app.get("*", (_req, res) => {
    res.sendFile(path.join(publicDir, "index.html"));
  });
}

app.listen(config.PORT, "0.0.0.0", () => {
  logInfo(`Sunucu basladi: ${config.PORT}`);
});
