/**
 * src/config/secrets.js
 *
 * Centralized loader for all sensitive credentials.
 *
 * Philosophy:
 *   - All secrets come from environment variables only.
 *   - config.json must never contain real secrets.
 *   - Only WEBEX_BOT_TOKEN is strictly required at startup (core bot functionality).
 *   - Other services (ServiceChannel, xAI, etc.) are optional. Features that need
 *     them will fail with a clear error when actually used.
 */

function requireEnv(name) {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Missing required environment variable: ${name}`);
  }
  return value;
}

function optionalEnv(name) {
  return process.env[name] || null;
}

export function loadSecrets() {
  return {
    // Core requirement — the bot cannot function without this
    webex: {
      token: requireEnv('WEBEX_BOT_TOKEN'),
      baseUrl: optionalEnv('WEBEX_BASE_URL') || 'https://webexapis.com/v1',
    },

    // ServiceChannel credentials — required only when ServiceChannel features are used
    serviceChannel: {
      clientId:     optionalEnv('SC_CLIENT_ID'),
      clientSecret: optionalEnv('SC_CLIENT_SECRET'),
      username:     optionalEnv('SC_USERNAME'),
      password:     optionalEnv('SC_PASSWORD'),
      baseUrl:      optionalEnv('SC_BASE_URL')     || 'https://api.servicechannel.com/v3',
      oauthUrl:     optionalEnv('SC_OAUTH_URL')    || 'https://login.servicechannel.com/oauth/token',
    },

    // xAI — required only when summarization features are used
    xai: {
      token: optionalEnv('XAI_TOKEN'),
      model: optionalEnv('XAI_MODEL') || 'grok-4-1-fast-reasoning',
    },

    // Secondary integrations — all optional
    red: {
      clientId:   optionalEnv('RED_CLIENT_ID'),
      apiKey:     optionalEnv('RED_API_KEY'),
      companyIDs: optionalEnv('RED_COMPANY_IDS') ? optionalEnv('RED_COMPANY_IDS').split(',') : [],
    },

    meraki: {
      apiKey: optionalEnv('MERAKI_API_KEY'),
      orgId:  optionalEnv('MERAKI_ORG_ID'),
    },

    atlas: {
      authKey: optionalEnv('ATLAS_AUTH_KEY'),
    },

    optisign: {
      apiKey: optionalEnv('OPTISIGN_API_KEY'),
    },

    fedex: {
      clientId: optionalEnv('FEDEX_CLIENT_ID'),
      clientSecret: optionalEnv('FEDEX_CLIENT_SECRET'),
      accountNumber: optionalEnv('FEDEX_ACCOUNT_NUMBER'),
      apiBase: optionalEnv('FEDEX_API_BASE') || 'https://apis.fedex.com',
    },
  };
}

export default loadSecrets;