import http from 'http';
import dotenv from 'dotenv';
import path from 'path';

// Load environment variables from .env file FIRST
dotenv.config({ path: path.resolve(__dirname, '../.env') });
import { initializeGoogleSecretManager } from './services/googleSecretManager.service';
import { seedDefaultActivityTypes } from './services/activityTypeSeed.service';
import { stopQueueMetrics } from './utils/queueMetrics';

// Dynamic imports will be used inside startServer to ensure secrets are loaded first
import { emailService } from './services/email.service';

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

// Start server
const startServer = async (): Promise<void> => {
  try {
    // Initialize Google Secret Manager before starting server
    // This will merge secrets from GCS into process.env if enabled
    console.log('🔐 Initializing secrets...');
    await initializeGoogleSecretManager();

    // Dynamically import everything else after secrets are loaded
    const app = require('./app').default;
    const { initSocket } = require('./realtime/socket');
    require('./queues/tatWorker'); // Initialize TAT worker
    const { logTatConfig } = require('./config/tat.config');
    const { logSystemConfig } = require('./config/system.config');
    const { initializeHolidaysCache } = require('./utils/tatTimeUtils');
    const { seedDefaultConfigurations } = require('./services/configSeed.service');
    const { startPauseResumeJob } = require('./jobs/pauseResumeJob');
    require('./queues/pauseResumeWorker'); // Initialize pause resume worker
    const { initializeQueueMetrics } = require('./utils/queueMetrics');
    const { emailService } = require('./services/email.service');

    // Re-initialize email service after secrets are loaded (in case SMTP credentials were loaded)
    // This ensures the email service uses production SMTP if credentials are available
    try {
      await emailService.initialize();
      console.log('📧 Email service re-initialized after secrets loaded');
    } catch (error) {
      console.warn('⚠️  Email service re-initialization warning (will use test account if SMTP not configured):', error);
    }

    // Re-initialize email service after secrets are loaded (in case SMTP credentials were loaded)
    // This ensures the email service uses production SMTP if credentials are available
    try {
      await emailService.initialize();
      console.log('📧 Email service re-initialized after secrets loaded');
    } catch (error) {
      console.warn('⚠️  Email service re-initialization warning (will use test account if SMTP not configured):', error);
    }

    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);
    }

    // Seed default activity types if table is empty
    try {
      await seedDefaultActivityTypes();
    } catch (error) {
      console.error('⚠️  Activity type seeding error:', error);
    }

    // Initialize holidays cache for TAT calculations
    try {
      await initializeHolidaysCache();
    } catch (error) {
      // Silently fall back to weekends-only TAT calculation
    }

    // Start scheduled jobs
    startPauseResumeJob();

    // Initialize queue metrics collection for Prometheus
    initializeQueueMetrics();

    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');
  stopQueueMetrics();
  process.exit(0);
});

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

startServer();