/**
 * Server-side environment access.
 *
 * Every value is read through here so nothing reaches into `process.env` ad hoc, and so
 * a missing or malformed setting fails in one predictable place. Nothing in this module
 * may be imported from a client component — it would leak secrets into the bundle.
 */

import 'server-only'

function required(key: string): string {
  const value = process.env[key]
  if (!value) {
    throw new Error(
      `Missing required environment variable ${key}. Copy .env.example to .env and run \`npm run check:env\`.`,
    )
  }
  return value
}

function number(key: string, fallback: number): number {
  const raw = process.env[key]
  if (!raw) return fallback
  const parsed = Number(raw)
  return Number.isFinite(parsed) ? parsed : fallback
}

function boolean(key: string, fallback: boolean): boolean {
  const raw = process.env[key]
  if (raw === undefined) return fallback
  return raw === 'true' || raw === '1'
}

export const env = {
  get isProduction() {
    return process.env.NODE_ENV === 'production'
  },
  get authSecret() {
    const secret = required('AUTH_SECRET')
    if (secret.length < 32) throw new Error('AUTH_SECRET must be at least 32 characters')
    return secret
  },
  get sessionTtlHours() {
    return number('AUTH_SESSION_TTL_HOURS', 8)
  },
  get maxFailedLogins() {
    return number('AUTH_MAX_FAILED_LOGINS', 5)
  },
  get lockoutMinutes() {
    return number('AUTH_LOCKOUT_MINUTES', 15)
  },
  get demoAccountsEnabled() {
    return boolean('DEMO_ACCOUNTS_ENABLED', false)
  },
  get rateLimitWindowMs() {
    return number('RATE_LIMIT_WINDOW_MS', 60_000)
  },
  get rateLimitMaxRequests() {
    return number('RATE_LIMIT_MAX_REQUESTS', 240)
  },
  get rateLimitLoginMax() {
    return number('RATE_LIMIT_LOGIN_MAX', 10)
  },
  get telemetryTickMs() {
    return number('TELEMETRY_TICK_MS', 3000)
  },
  /** Optional external inference service (§40). Empty means use the built-in engine. */
  get aiServiceUrl() {
    return process.env.AI_SERVICE_URL || null
  },
  get aiServiceToken() {
    return process.env.AI_SERVICE_TOKEN || null
  },
}

/** Values that are safe to expose to the browser. */
export const publicConfig = {
  appName: process.env.NEXT_PUBLIC_APP_NAME || 'NABDH',
  defaultLocale: (process.env.NEXT_PUBLIC_DEFAULT_LOCALE || 'ar') as 'ar' | 'en',
  demoData: process.env.NEXT_PUBLIC_DEMO_DATA !== 'false',
}
