/**
 * Phase 4 — server-driven auth-provider gating.
 *
 * Probes env at module load. The result is captured at boot, NOT on every request:
 *   - matches the ops contract (operators set the env, restart the backend, the flag
 *     flips). In dev this means a backend restart is required after editing .env.
 *   - keeps the endpoint dirt cheap (no DB / env reads on the hot path).
 *
 * Replaces the old `--dart-define=ENABLE_SOCIAL_AUTH` build flag in client_app:
 * the client now reads `GET /api/shared/auth-providers` once on cold start and
 * hides Google/Apple buttons when the corresponding flag is `false`.
 */

const isPresent = (key) => {
  const v = process.env[key]
  return typeof v === 'string' && v.trim().length > 0
}

const allPresent = (...keys) => keys.every(isPresent)

// Snapshot taken at module load. If callers need a live value (rare — only env
// hot-reload tooling does), they can call `probeAuthProviders()` directly.
export const probeAuthProviders = () => ({
  google: {
    enabled: allPresent('GOOGLE_OAUTH_CLIENT_ID', 'GOOGLE_OAUTH_CLIENT_SECRET'),
  },
  apple: {
    enabled: allPresent(
      'APPLE_OAUTH_CLIENT_ID',
      'APPLE_OAUTH_TEAM_ID',
      'APPLE_OAUTH_KEY_ID',
      'APPLE_OAUTH_PRIVATE_KEY',
    ),
  },
  // Phone OTP is always available — we don't gate it on env. (The OTP stub or the
  // Fazpass integration is the only thing that varies, but neither prevents the
  // phone-OTP entry point from being available.)
  phone: { enabled: true },
})

let cached = null

export const getAuthProviders = () => {
  if (!cached) cached = probeAuthProviders()
  return cached
}

// Test-only: drop the cache so tests that mutate env between cases see the change.
export const _resetAuthProvidersCache = () => {
  cached = null
}
