import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
dotenv.config({ path: join(__dirname, '..', '.env') });

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: process.env.REDIS_URL ?? null,
  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: (process.env.API_BASE_URL ?? '').replace(/\/$/, '') || null,
  rewardsEndpointPath: (() => {
    let p = process.env.REWARDS_ENDPOINT_PATH ?? '';
    if (!p) return null;
    if (!p.startsWith('/')) p = '/' + p;
    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),
  disconnectStatusMs: numberEnv('DISCONNECT_STATUS_MS', 1000),
  disconnectForfeitMs: numberEnv('DISCONNECT_FORFEIT_MS', 10000),
};
