import cron from "node-cron";
import type { Request, Response } from "express";
import { io, app, server } from "./src/config/socket.io";
import { setupCleanupCron } from "./src/utils/cleanupCron";

// Socket.io events
io.on("connection", (socket) => {
  console.log("✅ A user connected:", socket.id);

  socket.on("disconnect", () => {
    console.log("❌ User disconnected:", socket.id);
  });
});

// Add this route to send message to browser
app.get("/", (req: Request, res: Response) => {
  res.send(
    `🔥 Hello Node.js + TypeScript With Postgresql Database Server Listening..`
  );
});

// will run Every hour at minute 0
cron.schedule("0 * * * *", () => {
  console.log("✅ Running cron job every minute");
});


// Run server
server.listen(process.env.PORT, () => {
  console.log(`✅ Server running at http://localhost:${process.env.PORT}`);

  // Start cleanup cron job
  setupCleanupCron();
});


// 404 handler
app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: `Route ${req.originalUrl} not found`,
  });
});

// Graceful shutdown
process.on("SIGTERM", () => {
  server.close(() => {
    console.log("Server closed gracefully");
    process.exit(0);
  });
});