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

dotenv.config({ path: path.resolve(__dirname, '../../.env') });
dotenv.config({ path: path.resolve(process.cwd(), '.env'), override: false });

const parseIntSafe = (value, fallback, min, max) => {
  const parsed = Number.parseInt(String(value ?? ''), 10);
  if (Number.isNaN(parsed)) return fallback;
  return Math.max(min, Math.min(max, parsed));
};

const parseList = (value, fallback = []) => {
  if (typeof value !== 'string') return fallback;
  const items = value
    .split(',')
    .map((item) => item.trim())
    .filter(Boolean);
  return items.length ? items : fallback;
};

module.exports = {
  NODE_ENV: process.env.NODE_ENV || 'development',
  PORT: parseIntSafe(process.env.PORT, 3000, 1, 65535),
  CORS_ORIGINS: parseList(process.env.CORS_ORIGINS, ['http://localhost:4200']),

  PGHOST: process.env.PGHOST || 'localhost',
  PGUSER: process.env.PGUSER || 'postgres',
  PGPASSWORD: process.env.PGPASSWORD || '1234',
  PGDATABASE: process.env.PGDATABASE || 'invima',
  PGPORT: parseIntSafe(process.env.PGPORT, 5432, 1, 65535),
  PGPOOL_MAX: parseIntSafe(process.env.PGPOOL_MAX, 8, 1, 30),

  SOCRATA_APP_TOKEN: process.env.SOCRATA_APP_TOKEN || '',

  AUTH_TOKEN_SECRET: process.env.AUTH_TOKEN_SECRET || 'dev_token_secret_change_me',
  AUTH_SESSION_HOURS: parseIntSafe(process.env.AUTH_SESSION_HOURS, 12, 1, 168),
  ADMIN_USERNAME: process.env.ADMIN_USERNAME || 'admin',
  ADMIN_PASSWORD: process.env.ADMIN_PASSWORD || 'Admin123*',
  ADMIN_FULL_NAME: process.env.ADMIN_FULL_NAME || 'Administrador INVIMA'
};
