<?php
/**
 * Live check: publicSiteMappings/{normalizedSubdomain} empty (and not reserved).
 */
require_once __DIR__ . '/_super_admin_common.php';
require_once __DIR__ . '/sa_client_bootstrap_template.php';

$body = sa_require_post_json();
$sess = sa_require_super_admin_session_with_db();
$dbUrl = $sess[2];
$accessToken = $sess[3];

$raw = isset($body['subdomain']) ? trim((string) $body['subdomain']) : '';
$sub = sa_normalize_subdomain($raw);

if ($sub === '' || strlen($sub) < 2) {
    sa_json_response(200, ['status' => 'success', 'available' => false, 'normalized' => $sub, 'reason' => 'invalid']);
}

if (in_array($sub, sa_reserved_subdomains_list(), true)) {
    sa_json_response(200, ['status' => 'success', 'available' => false, 'normalized' => $sub, 'reason' => 'reserved']);
}

$snap = firebase_rtdb_get($dbUrl, 'publicSiteMappings/' . $sub, $accessToken);
if (isset($snap['error'])) {
    sa_json_response(500, ['status' => 'error', 'message' => $snap['error']]);
}

$available = ($snap['data'] ?? null) === null;
sa_json_response(200, [
    'status' => 'success',
    'available' => $available,
    'normalized' => $sub,
]);
