import app from './app';
import http from 'http';
import { initSocket } from './realtime/socket';
import './queues/tatWorker'; // Initialize TAT worker
import { logTatConfig } from './config/tat.config';
import { logSystemConfig } from './config/system.config';
import { initializeHolidaysCache } from './utils/tatTimeUtils';
import { seedDefaultConfigurations } from './services/configSeed.service';

const PORT: number = parseInt(process.env.PORT || '5000', 10);

// Start server
const startServer = async (): Promise<void> => {
  try {
    const server = http.createServer(app);
    initSocket(server);
    
    // Seed default configurations if table is empty
    try {
      await seedDefaultConfigurations();
    } catch (error) {
      console.error('⚠️  Configuration seeding error:', error);
    }
    
    // Initialize holidays cache for TAT calculations
    try {
      await initializeHolidaysCache();
    } catch (error) {
      // Silently fall back to weekends-only TAT calculation
    }
    
    server.listen(PORT, () => {
      console.log(`🚀 Server running on port ${PORT} | ${process.env.NODE_ENV || 'development'}`);
    });
  } catch (error) {
    console.error('❌ Unable to start server:', error);
    process.exit(1);
  }
};

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

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

startServer();