const dotenv = require('dotenv');

let loaded = false;

const loadEnv = () => {
  if (loaded) return;
  dotenv.config({ path: '.env' });
  dotenv.config({ path: '.env.local' });
  loaded = true;
};

const parseOriginList = (value = '') =>
  String(value)
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);

const validateEnv = (env = process.env) => {
  const isProduction = String(env.NODE_ENV || '').toLowerCase() === 'production';
  const issues = [];

  if (!String(env.DATABASE || '').trim()) {
    issues.push('Missing required environment variable: DATABASE');
  }

  if (String(env.JWT_SECRET || '').trim().length < 24) {
    issues.push('JWT_SECRET must be at least 24 characters long');
  }

  if (isProduction) {
    if (parseOriginList(env.CORS_ALLOWED_ORIGINS).length === 0) {
      issues.push('CORS_ALLOWED_ORIGINS must be set in production');
    }
    if (String(env.INTEGRATION_ENCRYPTION_KEY || '').trim().length < 24) {
      issues.push('INTEGRATION_ENCRYPTION_KEY must be set to a strong value in production');
    }
  }

  return issues;
};

const getRuntimeConfig = (env = process.env) => ({
  nodeEnv: String(env.NODE_ENV || 'development').toLowerCase(),
  isProduction: String(env.NODE_ENV || '').toLowerCase() === 'production',
  port: Number(env.PORT || 8888),
  database: env.DATABASE,
  corsAllowedOrigins: parseOriginList(env.CORS_ALLOWED_ORIGINS),
  trustProxy: env.TRUST_PROXY === 'true',
  jsonLimit: env.JSON_BODY_LIMIT || '1mb',
  urlencodedLimit: env.URLENCODED_BODY_LIMIT || '1mb',
  authWindowMs: Number(env.AUTH_RATE_LIMIT_WINDOW_MS || 15 * 60 * 1000),
  authMax: Number(env.AUTH_RATE_LIMIT_MAX || 20),
  apiWindowMs: Number(env.API_RATE_LIMIT_WINDOW_MS || 60 * 1000),
  apiMax: Number(env.API_RATE_LIMIT_MAX || 600),
});

module.exports = {
  loadEnv,
  validateEnv,
  getRuntimeConfig,
};
