"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const cors_1 = __importDefault(require("cors"));
const express_1 = __importDefault(require("express"));
const http_1 = __importDefault(require("http"));
const socket_io_1 = require("socket.io");
const database_js_1 = require("./config/database.js");
const env_js_1 = require("./config/env.js");
const auth_js_1 = require("./middleware/auth.js");
const index_js_1 = require("./routes/index.js");
const socketHandlers_js_1 = require("./socket/socketHandlers.js");
const app = (0, express_1.default)();
const server = http_1.default.createServer(app);
const io = new socket_io_1.Server(server, {
    cors: {
        methods: ["GET", "POST", "PUT", "DELETE"],
        origin: "http://localhost:5173",
    },
});
app.use((0, cors_1.default)({
    methods: ["GET", "POST", "PUT", "DELETE"],
    origin: "http://localhost:5173",
}));
app.use(express_1.default.json({ limit: "5mb" }));
app.use("/api", index_js_1.apiRoutes);
app.get("/health", (_, res) => {
    res.json({ status: "OK", timestamp: new Date().toISOString() });
});
io.use(auth_js_1.authenticateSocket);
io.on("connection", async (socket) => {
    await (0, socketHandlers_js_1.handleConnection)(io, socket);
});
app.use((err, _req, res, _next) => {
    console.error("Unhandled error:", err);
    res.status(500).json({
        success: false,
        error: env_js_1.env.NODE_ENV === "production" ? "Internal server error" : err.message,
    });
});
const startServer = async () => {
    try {
        await (0, database_js_1.connectDatabase)();
        server.listen(env_js_1.env.PORT, () => {
            console.log(`🚀 Server running on port ${env_js_1.env.PORT}`);
            console.log(`📊 Environment: ${env_js_1.env.NODE_ENV}`);
            console.log(`🔗 CORS Origin: ${env_js_1.env.CORS_ORIGIN}`);
        });
    }
    catch (error) {
        console.error("Failed to start server:", error);
        process.exit(1);
    }
};
process.on("SIGTERM", () => {
    console.log("SIGTERM received, shutting down gracefully...");
    server.close(() => {
        console.log("HTTP server closed");
        process.exit(0);
    });
});
(async () => {
    await startServer();
})();
