/**
 * Runtime Context Helpers
 * For route-based environment access via X-Runtime-Environment header
 */

function getRuntimeContext(options = {}) {
  return (options || {}).runtimeContext || null;
}

function getRuntimeEnvironment(options = {}) {
  const runtimeContext = getRuntimeContext(options);
  if (!runtimeContext) return null;

  // Read from header (route-based mode)
  // SECURITY: Only allow 'production' and 'stage' from header
  // to prevent unauthorized access to dev data
  if (runtimeContext.headerEnvironment === 'production') return 'production';
  if (runtimeContext.headerEnvironment === 'stage') return 'stage';

  return null;
}

function getRuntimeProjectSlug(options = {}) {
  const runtimeContext = getRuntimeContext(options);
  return runtimeContext?.headerProjectSlug || null;
}

function applyRuntimeEnvironment(where = {}, options = {}) {
  const environment = getRuntimeEnvironment(options);
  if (!environment) return where;

  return {
    ...where,
    environment,
  };
}

function applyRuntimeProjectFilter(projectInclude = {}, options = {}) {
  const projectSlug = getRuntimeProjectSlug(options);
  if (!projectSlug) return projectInclude;

  return {
    ...projectInclude,
    required: true,
    where: {
      ...(projectInclude.where || {}),
      slug: projectSlug,
    },
  };
}

module.exports = {
  applyRuntimeEnvironment,
  applyRuntimeProjectFilter,
  getRuntimeEnvironment,
  getRuntimeProjectSlug,
};
