const express = require('express');
const http = require('http');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
require('dotenv').config();

const domainRoutes = require('./routes/domainRoutes');
const messagingRoutes = require('./routes/messagingRoutes');
const gameforgeRoutes = require('./routes/gameforgeRoutes');
const callRoutes = require('./routes/callRoutes');
const socketService = require('./services/socketService');

const path = require('path');

const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;

// Trust proxy for Codespaces/containers
app.set('trust proxy', 1);

// Security middleware
app.use(helmet());
app.use(cors({
  origin: process.env.FRONTEND_URL || 'https://atx-connect.up.railway.app',
  credentials: true
}));

// Rate limiting
const limiter = rateLimit({
  windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000, // 15 minutes
  max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100,
  message: 'Too many requests from this IP, please try again later.',
  standardHeaders: true,
  legacyHeaders: false,
});

app.use('/api/', limiter);

// Body parsing middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// Serve Astro build as main site
app.use(express.static(path.join(__dirname, '../../astro-site/dist')));

// Serve React app at /app
app.use('/app', express.static(path.join(__dirname, '../frontend/dist')));

// API routes
app.use('/api/passport/domain', domainRoutes);
app.use('/api/messaging', messagingRoutes);
app.use('/api/gameforge', gameforgeRoutes);
app.use('/api/calls', callRoutes);

// Initialize Socket.io
const io = socketService.initialize(httpServer);
app.set('io', io); // Make io available in routes

// 404 handler
app.use((req, res) => {
  res.status(404).json({
    success: false,
    error: 'Endpoint not found'
  });
});

// Error handler
app.use((err, req, res, next) => {
  console.error('Server error:', err);
  res.status(500).json({
    success: false,
    error: process.env.NODE_ENV === 'development' ? err.message : 'Internal server error'
  });
});

// Start server - bind to 0.0.0.0 for Railway/containers
httpServer.listen(PORT, '0.0.0.0', () => {
  console.log(`
╔═══════════════════════════════════════════════════════╗
║   AeThex Connect - Communication Platform            ║
║   Server running on port ${PORT}                        ║
║   Environment: ${process.env.NODE_ENV || 'development'}                     ║
╚═══════════════════════════════════════════════════════╝
  `);
  console.log(`Health check: http://localhost:${PORT}/health`);
  console.log(`API Base URL: http://localhost:${PORT}/api`);
  console.log(`Socket.io: Enabled`);
});

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM received, shutting down gracefully...');
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('SIGINT received, shutting down gracefully...');
  process.exit(0);
});

module.exports = app;
