// src/index.js
const express = require('express');
const cors = require('cors');
const config = require('./config');
const authRoutes = require('./routes/authRoutes');
const userRoutes = require('./routes/userRoutes');
// === ADDED FOR RATE LIMITING ===
const { initRedis } = require('./services/redisClient');

const app = express();

// === ADDED FOR RATE LIMITING ===
// Trust proxy to get correct client IP (important for rate limiting by IP)
// Set this if your app is behind a reverse proxy (nginx, load balancer, etc.)
if (process.env.TRUST_PROXY === 'true' || process.env.TRUST_PROXY === '1') {
  app.set('trust proxy', true);
}

// === SECURITY HARDENING: CORS ===
// CORS configuration with strict origin whitelisting
// IMPORTANT: Never use wildcard '*' when credentials or tokens are involved
const allowAllOrigins =
  !config.isProduction && config.corsAllowedOrigins.length === 0;

if (allowAllOrigins) {
  // Development mode: allow all origins (only when no origins configured)
  // This is safe for development but should never be used in production
  console.warn('⚠️ CORS: Allowing all origins (development mode only)');
  app.use(cors());
} else {
  // === SECURITY HARDENING: CORS ===
  // Production mode: Only allow explicitly whitelisted origins
  // This prevents malicious websites from making requests to your API
  const corsOptions = {
    origin(origin, callback) {
      // Allow requests with no origin (mobile apps, Postman, etc.)
      if (!origin) {
        return callback(null, true);
      }
      
      // Check if origin is in whitelist
      if (config.corsAllowedOrigins.includes(origin)) {
        return callback(null, true);
      }
      
      // Origin not allowed
      console.warn(`CORS: Blocked origin: ${origin}`);
      return callback(new Error('Not allowed by CORS'));
    },
    credentials: true, // Allow cookies/credentials
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization'],
  };
  
  app.use(cors(corsOptions));
  app.use((err, req, res, next) => {
    if (err && err.message === 'Not allowed by CORS') {
      return res.status(403).json({ error: 'Origin not allowed' });
    }
    return next(err);
  });
}
app.use(express.json());

// 👇 This must be here to serve test.html
app.use(express.static('public'));

app.get('/health', (req, res) => {
  res.json({ ok: true });
});

app.use('/auth', authRoutes);
app.use('/users', userRoutes);

// === ADDED FOR RATE LIMITING ===
// Initialize Redis connection (falls back gracefully if not available)
initRedis().catch((err) => {
  console.warn('Redis initialization warning:', err.message);
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Auth service running at http://localhost:${PORT}`);
});
