import dotenv from 'dotenv';
dotenv.config();

import express from 'express';
import http from 'http';
import { createWebSocketServer } from './ws';
import sessionsRouter from './routes/sessions';
import authRouter from './api/auth';
import { authMiddleware } from './middleware/authMiddleware'; // Import the middleware
import cors from 'cors';
import { v4 as uuidv4 } from 'uuid';
import { sessions, SessionState } from './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 = express();
const server = http.createServer(app);

// Middleware
app.use(express.json());
const allowedOrigins = process.env.CORS_ORIGIN ? process.env.CORS_ORIGIN.split(',') : [];

const corsOptions = {
  origin: (origin: string | undefined, callback: (err: Error | null, allow?: boolean) => void) => {
    // 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(cors(corsOptions));

// Public API Routes
app.use('/api/auth', authRouter);

// Public route for creating a new session
app.post('/sessions', (req, res) => {
  const sessionId = uuidv4();
  sessions.set(sessionId, {
    state: 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, sessionsRouter);

// Create and attach WebSocket server
createWebSocketServer(server);

const PORT = process.env.PORT || 8000;

server.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
