import express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';
import cors from 'cors';
import dotenv from 'dotenv';
import mongoose from 'mongoose';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer, {
  cors: {
    origin: process.env.CLIENT_URL || 'http://localhost:5173',
    methods: ['GET', 'POST']
  }
});

app.use(cors());
app.use(express.json());

// Статичные файлы для медиа
app.use('/images', express.static(join(__dirname, '../public/images')));
app.use('/audio', express.static(join(__dirname, '../public/audio')));
app.use('/video', express.static(join(__dirname, '../public/video')));

// MongoDB connection (optional - можно использовать JSON файлы)
const connectDB = async () => {
  if (process.env.MONGODB_URI) {
    try {
      await mongoose.connect(process.env.MONGODB_URI);
      console.log('✅ MongoDB connected');
    } catch (error) {
      console.log('⚠️  MongoDB not connected, using JSON storage');
    }
  } else {
    console.log('⚠️  No MongoDB URI, using JSON storage');
  }
};

// Хранилище активных игр в памяти
const activeGames = new Map();

// Импорт роутов и сокет обработчиков
import questionsRouter from './routes/questions.js';
import gamesRouter from './routes/games.js';
import { setupSocketHandlers } from './socket/handlers.js';

app.use('/api/questions', questionsRouter);
app.use('/api/games', gamesRouter);

// WebSocket обработчики
setupSocketHandlers(io, activeGames);

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

connectDB().then(() => {
  httpServer.listen(PORT, () => {
    console.log(`🚀 Server running on port ${PORT}`);
  });
});

export { io, activeGames };
