const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const dotenv = require('dotenv');
const path = require('path');
const { testConnections, closeAllConnections } = require('./config/database');
const authMiddleware = require('./middleware/auth');
const { 
  securityHeaders, 
  generalLimiter, 
  authLimiter, 
  validateInput,
  sanitizeRequest
} = require('./middleware/security');
const iaLogger = require('./services/iaLogger');

const recettesRoutes = require('./routes/recettes');
const flotteRoutes = require('./routes/flotte');
const personnelRoutes = require('./routes/personnel');
const authRoutes = require('./routes/auth');
const iaRoutes = require('./routes/ia');

dotenv.config();

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

const API_PREFIX = process.env.API_PREFIX || '/apidecisionnelAssist';

app.use(securityHeaders);
app.use(morgan('combined'));

const corsOptions = {
  origin: process.env.ALLOWED_ORIGINS ? process.env.ALLOWED_ORIGINS.split(',') : ['http://localhost:3000', 'http://localhost:8080'],
  credentials: true,
  optionsSuccessStatus: 200
};
app.use(cors(corsOptions));

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(sanitizeRequest);

app.use(generalLimiter);

app.use(`${API_PREFIX}/auth`, authLimiter, authRoutes);
app.use(`${API_PREFIX}/ia`, validateInput, iaRoutes);
app.use(`${API_PREFIX}/recettes`, validateInput, recettesRoutes);
app.use(`${API_PREFIX}/flotte`, validateInput, flotteRoutes);
app.use(`${API_PREFIX}/personnel`, validateInput, personnelRoutes);

app.get(`${API_PREFIX}/health`, (req, res) => {
  res.json({ 
    status: 'OK', 
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

app.get('/', (req, res) => {
  res.json({
    success: true,
    message: 'API DecisionnelAssist - Transub',
    version: '1.0.0',
    apiPrefix: API_PREFIX,
    endpoints: [
      `${API_PREFIX}/auth`,
      `${API_PREFIX}/ia/query`,
      `${API_PREFIX}/ia/suggestions`,
      `${API_PREFIX}/ia/types`,
      `${API_PREFIX}/ia/logs`,
      `${API_PREFIX}/ia/statistics`,
      `${API_PREFIX}/ia/dictionary`,
      `${API_PREFIX}/recettes`,
      `${API_PREFIX}/flotte`,
      `${API_PREFIX}/personnel`,
      `${API_PREFIX}/health`
    ]
  });
});

app.use((req, res) => {
  res.status(404).json({
    success: false,
    message: 'Route non trouvée'
  });
});

app.use((err, req, res, next) => {
  console.error('[ERROR]', err.stack);
  res.status(500).json({
    success: false,
    message: 'Erreur interne du serveur'
  });
});

const server = app.listen(PORT, async () => {
  console.log(`🚀 Serveur démarré sur le port ${PORT}`);
  
  try {
    await iaLogger.createTables();
    console.log('✅ Tables de logging créées');
  } catch (error) {
    console.error('⚠️ Tables de logging non créées:', error.message);
  }
});

process.on('SIGTERM', async () => {
  console.log('🛑 Arrêt du serveur...');
  await closeAllConnections();
  server.close(() => {
    console.log('✅ Serveur arrêté');
    process.exit(0);
  });
});

process.on('SIGINT', async () => {
  console.log('🛑 Arrêt du serveur...');
  await closeAllConnections();
  server.close(() => {
    console.log('✅ Serveur arrêté');
    process.exit(0);
  });
});

module.exports = app;