/**
 * Configuration module for AEM Asset Upload Sample
 * Loads and validates environment variables
 */

require('dotenv').config();
const { hasServiceCredentials, getAccessToken } = require('./auth');

/**
 * Validates required configuration
 * @param {Object} options - Validation options
 * @param {boolean} options.requireRemoteUrls - Whether to validate remote URL configuration
 * @throws {Error} If required configuration is missing
 */
function validateConfig(options = {}) {
  if (!process.env.AEM_URL) {
    throw new Error('AEM_URL is required. Please set it in your .env file.');
  }

  // Check if at least one authentication method is provided
  const hasBasicAuth = process.env.AEM_USERNAME && process.env.AEM_PASSWORD;
  const hasBearerToken = process.env.AEM_BEARER_TOKEN;
  const hasServiceCreds = hasServiceCredentials();

  if (!hasBasicAuth && !hasBearerToken && !hasServiceCreds) {
    throw new Error(
      'Authentication credentials are required. Please provide one of:\n' +
      '  1. Service Credentials (RECOMMENDED): AEM_SERVICE_CREDENTIALS_FILE in your .env file\n' +
      '  2. Bearer Token: AEM_BEARER_TOKEN in your .env file\n' +
      '  3. Basic Auth (dev only): AEM_USERNAME/AEM_PASSWORD in your .env file'
    );
  }

  if (!process.env.TARGET_FOLDER) {
    throw new Error('TARGET_FOLDER is required. Please set it in your .env file.');
  }

  // Validate remote URLs if required (for DirectBinaryUpload example)
  if (options.requireRemoteUrls) {
    if (!process.env.REMOTE_FILE_URL_1) {
      throw new Error(
        'REMOTE_FILE_URL_1 is required for DirectBinaryUpload example. ' +
        'Please set it in your .env file.'
      );
    }
  }
}

/**
 * Gets upload options for aem-upload library
 * @returns {Promise<Object>} Upload options with authentication
 */
async function getUploadOptions() {
  // Remove trailing slash from AEM_URL if present
  const aemUrl = process.env.AEM_URL.replace(/\/$/, '');
  
  const options = {
    url: aemUrl,
    log: {
      level: process.env.DEBUG === 'true' ? 'debug' : 'info'
    }
  };

  // Add authentication (priority order: Service Credentials > Bearer Token > Basic Auth)
  if (hasServiceCredentials()) {
    // Service Credentials - Generate access token from JWT (RECOMMENDED for production)
    const accessToken = await getAccessToken(process.env.AEM_SERVICE_CREDENTIALS_FILE);
    options.headers = {
      Authorization: `Bearer ${accessToken}`
    };
  } else if (process.env.AEM_BEARER_TOKEN) {
    // Bearer Token - Use provided token (for manual testing)
    options.headers = {
      Authorization: `Bearer ${process.env.AEM_BEARER_TOKEN}`
    };
  } else if (process.env.AEM_USERNAME && process.env.AEM_PASSWORD) {
    // Basic Auth - Base64 encoded credentials (for development only)
    const credentials = Buffer.from(`${process.env.AEM_USERNAME}:${process.env.AEM_PASSWORD}`).toString('base64');
    options.headers = {
      Authorization: `Basic ${credentials}`
    };
  }

  return options;
}

/**
 * Gets the target folder path in AEM DAM
 * @returns {string} Target folder path
 */
function getTargetFolder() {
  return process.env.TARGET_FOLDER;
}

/**
 * Gets remote file URLs from environment configuration
 * @returns {Array<string>} Array of remote file URLs
 */
function getRemoteFileUrls() {
  const urls = [];
  
  // Collect all REMOTE_FILE_URL_* environment variables
  for (let i = 1; i <= 10; i++) {
    const urlKey = `REMOTE_FILE_URL_${i}`;
    if (process.env[urlKey]) {
      urls.push(process.env[urlKey]);
    }
  }
  
  return urls;
}

module.exports = {
  validateConfig,
  getUploadOptions,
  getTargetFolder,
  getRemoteFileUrls
};

