import app from './app';
import { env } from './config/env';
import { testConnection } from './config/database';
import fs from 'fs';
import path from 'path';

const startServer = async () => {
  try {
    // Tester la connexion MySQL avant de démarrer le serveur
    await testConnection();

    // Démarrer le planificateur automatique des rappels d'échéances de paiement
    const { startReminderScheduler } = await import('./services/paymentReminders.service');
    startReminderScheduler();

    const server = app.listen(env.PORT, () => {
      console.log(`🚀 Serveur démarré en mode ${env.NODE_ENV} sur le port ${env.PORT}`);
    });

    // Configuration des timeouts pour téléversements lourds (ex: vidéos 500 Mo)
    server.timeout = 20 * 60 * 1000; // 20 minutes
    server.keepAliveTimeout = 20 * 60 * 1000;
    server.headersTimeout = 21 * 60 * 1000;
  } catch (error: any) {
    console.error('❌ Impossible de démarrer le serveur:', error);
    
    // Log the error to a file for debugging on shared hosting
    try {
      const logPath = path.join(__dirname, '../../error.log');
      fs.writeFileSync(logPath, `Time: ${new Date().toISOString()}\nError: ${error.message}\nStack: ${error.stack}\n`);
    } catch (fsError) {
      console.error('Impossible d\'écrire dans error.log', fsError);
    }
    
    process.exit(1);
  }
};

startServer();
