/**
 * Server-side secrets for the web app. Mirrors apps/game-server/src/config.ts: development gets
 * explicit insecure fallbacks, production fails loudly instead of running with a guessable secret.
 * Only call these at request time (never at module scope) so `next build` needs no secrets.
 */
const isProduction = process.env.NODE_ENV === 'production';

const DEV_AUTH_SECRET = 'dev-only-insecure-secret-change-me-0123456789';

function firstSet(names: string[]): string | undefined {
  for (const name of names) {
    const value = process.env[name];
    if (value && value.length > 0) return value;
  }
  return undefined;
}

/** HMAC key for signed form tokens (shared AUTH_SECRET). */
export function formSecret(): string {
  const value = firstSet(['AUTH_SECRET']);
  if (value) return value;
  if (!isProduction) return DEV_AUTH_SECRET;
  throw new Error('Missing required environment variable AUTH_SECRET');
}

/** Salt for hashing IP addresses (rate limits only). Falls back to AUTH_SECRET. */
export function analyticsSalt(): string {
  const value = firstSet(['ANALYTICS_SALT', 'AUTH_SECRET']);
  if (value) return value;
  if (!isProduction) return DEV_AUTH_SECRET;
  throw new Error('Missing required environment variable ANALYTICS_SALT (or AUTH_SECRET)');
}
