/**
 * Africa Alert — server config (single source of truth).
 *
 * Crashes the process on startup if a required env var is missing in
 * production. The dev defaults are deliberately insecure; loud warnings
 * are emitted when they're used so the mistake is obvious in logs.
 *
 * Required env vars in production:
 *   - JWT_SECRET: HMAC key for signing/verifying auth tokens
 *   - ALLOWED_ORIGINS: comma-separated CORS allow-list (e.g. https://school.example.com)
 *
 * Optional env vars:
 *   - DB_PATH: SQLite file path (default: ../data/school.db relative to this file)
 *   - NODE_ENV: 'development' | 'production' (default: development)
 *   - PORT: HTTP port (default: 3001)
 *   - ALLOW_CLIENT_OFFLINE_MINT: when true, /api/auth/login response
 *     includes `offline_jwt_secret` so the client can mint JWTs while
 *     offline. Default: false in production, true in development.
 */
const path = require('path');

const NODE_ENV = process.env.NODE_ENV || 'development';
const IS_PROD = NODE_ENV === 'production';

const REQUIRED_IN_PROD = ['JWT_SECRET', 'ALLOWED_ORIGINS'];
if (IS_PROD) {
  const missing = REQUIRED_IN_PROD.filter((k) => !process.env[k]);
  if (missing.length > 0) {
    // eslint-disable-next-line no-console
    console.error(
      `[FATAL] server/src/config: required env vars missing in production: ${missing.join(', ')}`
    );
    // eslint-disable-next-line no-console
    console.error('Set them in .env or the orchestrator before starting the server.');
    process.exit(1);
  }
}

// Loud warning if dev fallbacks are in use. In dev we still let the server
// boot with a known insecure string so contributors can run without a .env
// file. In prod we crashed at the top of this file if JWT_SECRET is missing.
const DEV_FALLBACK_SECRET = 'dev-only-insecure-secret-do-not-use-in-production';
const JWT_SECRET_VALUE = process.env.JWT_SECRET
  || (IS_PROD ? null : DEV_FALLBACK_SECRET);

if (!IS_PROD && !process.env.JWT_SECRET) {
  // eslint-disable-next-line no-console
  console.warn(
    '[config] WARNING: JWT_SECRET is unset; using insecure dev fallback "' +
      DEV_FALLBACK_SECRET + '". NEVER run with this in production. Set JWT_SECRET in .env.'
  );
}

module.exports = {
  nodeEnv: NODE_ENV,
  isProd: IS_PROD,
  jwtSecret: JWT_SECRET_VALUE,
  allowedOrigins: (process.env.ALLOWED_ORIGINS || 'http://localhost:3000')
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean),
  dbPath: process.env.DB_PATH || path.join(__dirname, '..', '..', 'data', 'school.db'),
  port: parseInt(process.env.PORT || '3001', 10),
  // When true, /api/auth/login response includes `offline_jwt_secret` so
  // the client can mint JWTs while offline. Defaults to dev-only.
  allowClientOfflineMint:
    process.env.ALLOW_CLIENT_OFFLINE_MINT
      ? process.env.ALLOW_CLIENT_OFFLINE_MINT === 'true'
      : !IS_PROD,
};
