<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

$cfg = require __DIR__ . '/config.php';
require __DIR__ . '/lib/config_validation.php';

function json_response(int $code, array $payload): never {
  http_response_code($code);
  echo json_encode($payload, JSON_UNESCAPED_SLASHES);
  exit;
}

$report = config_health_report($cfg);

if (!$report['env_ok']) {
  json_response(500, [
    'ok' => false,
    'env_ok' => false,
    'missing_envs' => array_values($report['missing_envs']),
    'message' => 'Missing required environment variables',
  ]);
}

$payload = [
  'ok' => true,
  'env_ok' => true,
  'tenants_dir_ok' => $report['tenants_dir_ok'],
  'tenants_dir' => $report['tenants_dir'],
];

if (!$report['tenants_dir_ok']) {
  $payload['tenants_dir_error'] = $report['tenants_dir_error'];
}

$status = $report['tenants_dir_ok'] ? 200 : 500;
json_response($status, $payload);
