require('dotenv').config();

const config = {
  port: process.env.PORT || 5000,
  mongoUri: process.env.MONGO_URI || 'mongodb://127.0.0.1:27017/tracking-leaders',
  jwtSecret: process.env.JWT_SECRET || 'your-secret-key-change-in-production',
  jwtExpiresIn: process.env.JWT_EXPIRES_IN || '24h',
  nodeEnv: process.env.NODE_ENV || 'development',
  corsOrigin: process.env.CORS_ORIGIN ? process.env.CORS_ORIGIN.split(',') : ['http://localhost:5000'],
  geocodeUrl: process.env.GEOCODE_URL || 'https://nominatim.openstreetmap.org/search',
  geocodeUserAgent: process.env.GEOCODE_USER_AGENT || 'tracking-leaders-app/1.0 (admin@localhost)',
  geocodeMinDelayMs: parseInt(process.env.GEOCODE_MIN_DELAY_MS || '1100', 10)
};

// Validate required environment variables
const requiredVars = ['JWT_SECRET', 'MONGO_URI'];
const productionVars = ['ADMIN_THORSTEN_PASSWORD']; // Only warn in production

// In test environment, use defaults if not set
if (config.nodeEnv === 'test') {
  // Set test defaults
  if (!process.env.JWT_SECRET) process.env.JWT_SECRET = 'test-secret-key';
  if (!process.env.MONGO_URI) process.env.MONGO_URI = 'mongodb://localhost:27017/test';
} else {
  // Always validate critical vars (except in test)
  requiredVars.forEach(varName => {
    if (!process.env[varName]) {
      console.error(`❌ Fehler: ${varName} muss gesetzt sein!`);
      console.error(`   Tipp: Kopiere .env.example zu .env und fülle die Werte aus.`);
      process.exit(1);
    }
  });
}

// Warn about missing production-specific vars
if (config.nodeEnv === 'production') {
  productionVars.forEach(varName => {
    if (!process.env[varName]) {
      console.warn(`⚠️  Warnung: ${varName} sollte in Production gesetzt sein!`);
    }
  });
  
  // Check for insecure defaults in production
  if (config.jwtSecret === 'your-secret-key-change-in-production') {
    console.error('❌ Fehler: JWT_SECRET verwendet unsicheren Default-Wert!');
    process.exit(1);
  }
}

module.exports = config;
