"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const dotenv_1 = __importDefault(require("dotenv"));
dotenv_1.default.config();
const express_1 = __importDefault(require("express"));
const http_1 = __importDefault(require("http"));
const ws_1 = require("./ws");
const sessions_1 = __importDefault(require("./routes/sessions"));
const auth_1 = __importDefault(require("./api/auth"));
const authMiddleware_1 = require("./middleware/authMiddleware"); // Import the middleware
const cors_1 = __importDefault(require("cors"));
const uuid_1 = require("uuid");
const ws_2 = require("./ws"); // Import sessions and SessionState from ws/index.ts
console.log('index.ts: AUTH_PASSPHRASE:', process.env.AUTH_PASSPHRASE);
console.log('index.ts: SESSION_SECRET:', process.env.SESSION_SECRET);
console.log('index.ts: JWT_SECRET:', process.env.JWT_SECRET);
const app = (0, express_1.default)();
const server = http_1.default.createServer(app);
// Middleware
app.use(express_1.default.json());
const allowedOrigins = process.env.CORS_ORIGIN ? process.env.CORS_ORIGIN.split(',') : [];
const corsOptions = {
    origin: (origin, callback) => {
        // Allow same-origin requests (origin is undefined) and requests from the whitelisted origins
        if (!origin || allowedOrigins.includes(origin)) {
            callback(null, true);
        }
        else {
            console.warn(`CORS: Blocked request from origin: ${origin}`);
            callback(new Error('Not allowed by CORS'));
        }
    },
};
app.use((0, cors_1.default)(corsOptions));
// Public API Routes
app.use('/api/auth', auth_1.default);
// Public route for creating a new session
app.post('/sessions', (req, res) => {
    const sessionId = (0, uuid_1.v4)();
    ws_2.sessions.set(sessionId, {
        state: ws_2.SessionState.SETUP,
        topic: null,
        description: null,
        expectedResponses: 0,
        submittedCount: 0,
        responses: new Map(),
        clients: new Map(),
        finalResult: null,
    });
    console.log(`New session created: ${sessionId}`);
    res.status(201).json({ sessionId });
});
// Protected API Routes
app.use('/sessions', authMiddleware_1.authMiddleware, sessions_1.default);
// Create and attach WebSocket server
(0, ws_1.createWebSocketServer)(server);
const PORT = process.env.PORT || 8000;
server.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
