import { createServer } from 'http';
import { Server as SocketServer } from 'socket.io';
import app from './app';
import { notificationService } from '../notifications/notificationService';
import { collaborationService } from '../collaboration/collaborationService';
import * as dotenv from 'dotenv';

// Load environment variables
dotenv.config();

const PORT = process.env.API_PORT || 3000;

// Create HTTP server
const httpServer = createServer(app);

// Initialize Socket.io
const io = new SocketServer(httpServer, {
  cors: {
    origin: process.env.CORS_ORIGIN || '*',
    methods: ['GET', 'POST'],
    credentials: true
  },
  transports: ['websocket', 'polling']
});

// Initialize notification service with Socket.io
notificationService.initializeSocketServer(io);

// Initialize collaboration service with Socket.io
collaborationService.setSocketServer(io);

// Start server
httpServer.listen(PORT, () => {
  console.log(`🚀 API Server is running on port ${PORT}`);
  console.log(`📍 Health check: http://localhost:${PORT}/health`);
  console.log(`📝 Tasks API: http://localhost:${PORT}/api/tasks`);
  console.log(`🔌 Socket.io server ready for real-time connections`);
  console.log(`📧 Email notifications ${process.env.SMTP_USER ? 'enabled' : 'disabled'}`);
  console.log(`🤝 Real-time collaboration enabled with Y.js`);
});

// Graceful shutdown
process.on('SIGTERM', () => {
  console.log('SIGTERM signal received: closing HTTP server');
  httpServer.close(() => {
    console.log('HTTP server closed');
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  console.log('SIGINT signal received: closing HTTP server');
  httpServer.close(() => {
    console.log('HTTP server closed');
    process.exit(0);
  });
});

export { httpServer, io };