<?php
declare(strict_types=1);

/**
 * Lightweight helper for validating the API config at runtime.
 */

function config_env_value(string $key): string {
  $value = $_ENV[$key] ?? getenv($key) ?? '';
  return trim((string)$value);
}

function config_required_env_keys(): array {
  return [
    'TENANT_STORAGE_PATH',
    'YOCO_SECRET_KEY',
    'YOCO_WEBHOOK_SECRET',
    'WP_MASTER_KEY_B64',
  ];
}

function config_missing_env_keys(): array {
  $missing = [];
  foreach (config_required_env_keys() as $key) {
    if (config_env_value($key) === '') {
      $missing[] = $key;
    }
  }
  return $missing;
}

function config_tenants_dir_status(array $cfg): array {
  $dir = (string)($cfg['tenants_dir'] ?? '');
  $dir = $dir !== '' ? rtrim($dir, '/') : '';
  if ($dir === '') {
    return [
      'dir' => $dir,
      'ok' => false,
      'error' => 'tenants_dir not configured',
    ];
  }

  if (!is_dir($dir)) {
    return [
      'dir' => $dir,
      'ok' => false,
      'error' => 'directory missing',
    ];
  }

  if (!is_readable($dir)) {
    return [
      'dir' => $dir,
      'ok' => false,
      'error' => 'not readable',
    ];
  }

  if (!is_writable($dir)) {
    return [
      'dir' => $dir,
      'ok' => false,
      'error' => 'not writable',
    ];
  }

  return [
    'dir' => $dir,
    'ok' => true,
    'error' => null,
  ];
}

function config_health_report(array $cfg): array {
  $missing = config_missing_env_keys();
  $tenants = config_tenants_dir_status($cfg);

  return [
    'env_ok' => $missing === [],
    'missing_envs' => $missing,
    'tenants_dir_ok' => $tenants['ok'],
    'tenants_dir_error' => $tenants['error'],
    'tenants_dir' => $tenants['dir'],
  ];
}
