import dotenv from 'dotenv';

dotenv.config();

function required(name) {
  const value = process.env[name];
  if (!value) throw new Error(`Missing env var ${name}`);
  return value;
}

function numberEnv(name, fallback) {
  const raw = process.env[name];
  if (raw === undefined || raw === '') return fallback;
  const value = Number(raw);
  if (!Number.isFinite(value)) throw new Error(`Invalid number env var ${name}`);
  return value;
}

export const config = {
  port: numberEnv('PORT', 8088),
  publicWsUrl: process.env.PUBLIC_WS_URL ?? null,
  allowedOrigins: (process.env.ALLOWED_ORIGINS ?? '').split(',').map(s => s.trim()).filter(Boolean),

  redisUrl: required('REDIS_URL'),
  redisKeyPrefix: process.env.REDIS_KEY_PREFIX ?? 'pp:1v1:',

  mysql: {
    host: required('MYSQL_HOST'),
    port: numberEnv('MYSQL_PORT', 3306),
    user: required('MYSQL_USER'),
    password: required('MYSQL_PASSWORD'),
    database: required('MYSQL_DATABASE'),
    connectionLimit: numberEnv('MYSQL_CONNECTION_LIMIT', 20),
  },

  sharedSecret: required('PINGPONG_1V1_SHARED_SECRET'),
  apiBaseUrl: required('API_BASE_URL').replace(/\/$/, ''),
  rewardsEndpointPath: (() => {
    let p = required('REWARDS_ENDPOINT_PATH');
    if (!p.startsWith('/')) p = '/' + p;
    // Our PHP endpoint is a directory with index.php; Apache redirects to trailing slash.
    if (!p.endsWith('/')) p = p + '/';
    return p;
  })(),

  matchTickHz: numberEnv('MATCH_TICK_HZ', 30),
  redisSnapshotMs: numberEnv('REDIS_SNAPSHOT_MS', 1000),
  mysqlUpdateIntervalMs: numberEnv('MYSQL_UPDATE_INTERVAL_MS', 1000),
  reconnectGraceMs: numberEnv('RECONNECT_GRACE_MS', 15000),
};
