const path = require('path');
const dotenv = require('dotenv');

dotenv.config({ path: process.env.ENV_PATH || path.resolve(process.cwd(), '.env') });

const toBoolean = (value, fallback = false) => {
  if (typeof value === 'boolean') return value;
  if (typeof value === 'string') {
    return ['1', 'true', 'yes', 'on'].includes(value.toLowerCase());
  }
  return fallback;
};

const env = {
  nodeEnv: process.env.NODE_ENV || 'development',
  port: parseInt(process.env.PORT || '8080', 10),
  geminiApiKey: process.env.GEMINI_API_KEY,
  allowedOrigins: process.env.ALLOWED_ORIGINS || '*',
  redisUrl: process.env.REDIS_URL || 'redis://redis:6379',
  redisCacheTtlSeconds: parseInt(process.env.ISBN_CACHE_TTL_SECONDS || '21600', 10),
  jwt: {
    secret: process.env.JWT_SECRET || 'super-secret-key-change-me',
    expiresIn: process.env.JWT_EXPIRES_IN || '1h'
  },
  postgres: {
    host: process.env.POSTGRES_HOST || 'postgres',
    port: parseInt(process.env.POSTGRES_PORT || '5432', 10),
    database: process.env.POSTGRES_DB || 'bookibra',
    user: process.env.POSTGRES_USER || 'bookibra',
    password: process.env.POSTGRES_PASSWORD || 'bookibra'
  },
  flags: {
    enableRequestLogging: toBoolean(process.env.REQUEST_LOGGING, true)
  }
};

module.exports = env;
