import http from "http";
import cors from "cors";
import express from "express";
import helmet from "helmet";
import rateLimit from "express-rate-limit";
import { Server } from "socket.io";
import { env } from "./config/env.js";
import { connectDatabase } from "./config/db.js";
import { registerRoutes } from "./routes/index.js";
import { registerRealtime } from "./realtime/socket.js";

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: { origin: env.frontendUrl, credentials: true }
});

app.use(helmet());
app.use(cors({ origin: env.frontendUrl, credentials: true }));
app.use(express.json({ limit: "3mb" }));
app.use(express.urlencoded({ extended: true }));
app.use(rateLimit({ windowMs: 15 * 60 * 1000, max: 600 }));
app.set("io", io);

registerRealtime(io);
registerRoutes(app);

app.use((error, _request, response, _next) => {
  console.error(error);
  response.status(error.status || 500).json({ message: error.message || "Internal server error" });
});

await connectDatabase();

server.listen(env.port, () => {
  console.log(`OMOSALA API running on port ${env.port}`);
});
