const express = require('express');
const path = require('path');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const { syncDB } = require('./models');
const authRoutes = require('./routes/authRoutes');
const referralRoutes = require('./routes/referralRoutes');
const walletRoutes = require('./routes/walletRoutes');
const taskRoutes = require('./routes/taskRoutes');
const userRoutes = require('./routes/userRoutes');
const settingsRoutes = require('./routes/settingsRoutes');
const activityLogRoutes = require('./routes/activityLogRoutes');
const { seedSettings } = require('./controllers/settingsController');

const app = express();

// Middleware
app.use(helmet());
app.use(cors());
app.use(express.json());

// Rate Limiting General
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutos
  max: 500, // Limite de peticiones por IP
  standardHeaders: true,
  legacyHeaders: false,
});
app.use('/api', limiter);

// Rate Limiting Auth (Más estricto)
const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000,
  max: 100, // Aumentado para pruebas
  message: { message: 'Demasiados intentos, intente más tarde' }
});
app.use('/api/auth', authLimiter);

// Rutas API
app.use('/api/auth', authRoutes);
app.use('/api/referrals', referralRoutes);
app.use('/api/wallet', walletRoutes);
app.use('/api/tasks', taskRoutes);
app.use('/api/users', userRoutes);
app.use('/api/settings', settingsRoutes);
app.use('/api/logs', activityLogRoutes);

// Servir frontend en producción o si existe la carpeta dist
const frontendPath = path.join(__dirname, '../frontend/dist');
app.use(express.static(frontendPath));

app.get('*', (req, res) => {
  // Si es una ruta de API que no se encontró, pasar al siguiente middleware (404 json)
  if (req.path.startsWith('/api')) {
    return res.status(404).json({ message: 'API Route not found' });
  }
  // Enviar index.html para cualquier otra ruta (SPA)
  res.sendFile(path.join(frontendPath, 'index.html'), (err) => {
    if (err) {
      res.status(500).send(err);
    }
  });
});

const PORT = process.env.PORT || 5000;

const startServer = async () => {
  await syncDB();
  await seedSettings();
  app.listen(PORT, () => {
    console.log(`Servidor corriendo en el puerto ${PORT}`);
  });
};

startServer();
