<?php
/**
 * One-time CLI tool:
 * php api/legacy-admin-backfill.php
 *
 * Migrates legacy admin entries (email-keyed/random-keyed) to canonical admins/{uid}
 * without changing database rules.
 */
if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo "CLI only.\n";
    exit(1);
}

require_once __DIR__ . '/firebase-rtdb-admin.php';

$bootPath = __DIR__ . '/firebase-admin-bootstrap.local.php';
if (!is_readable($bootPath)) {
    fwrite(STDERR, "Missing firebase-admin-bootstrap.local.php\n");
    exit(1);
}
$boot = include $bootPath;
if (!is_array($boot)) {
    fwrite(STDERR, "Invalid bootstrap config.\n");
    exit(1);
}

$saPath = isset($boot['service_account_json_path']) ? trim((string) $boot['service_account_json_path']) : '';
$dbUrl = isset($boot['firebase_database_url']) ? trim((string) $boot['firebase_database_url']) : '';
$webKey = isset($boot['firebase_web_api_key']) ? trim((string) $boot['firebase_web_api_key']) : '';
if ($saPath === '' || $dbUrl === '' || $webKey === '' || $webKey === 'PASTE_FIREBASE_WEB_API_KEY_HERE') {
    fwrite(STDERR, "Bootstrap incomplete.\n");
    exit(1);
}

function lookup_uid_by_email($email, $webApiKey) {
    $url = 'https://identitytoolkit.googleapis.com/v1/accounts:createAuthUri?key=' . rawurlencode($webApiKey);
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode(['identifier' => $email, 'continueUri' => 'http://localhost']),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 20,
    ]);
    $res = curl_exec($ch);
    curl_close($ch);
    if ($res === false) return null;
    $data = json_decode($res, true);
    if (!is_array($data) || empty($data['registered'])) return null;

    $url2 = 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=' . rawurlencode($webApiKey);
    // Password unknown for legacy rows; cannot safely resolve uid via this endpoint.
    // Return null and let login-time compat endpoint handle real migration.
    return null;
}

$tok = firebase_service_account_access_token($saPath);
if (isset($tok['error'])) {
    fwrite(STDERR, "Token error: {$tok['error']}\n");
    exit(1);
}
$access = $tok['access_token'];

$clientsSnap = firebase_rtdb_get($dbUrl, 'clients', $access);
if (isset($clientsSnap['error']) || !is_array($clientsSnap['data'])) {
    fwrite(STDERR, "Could not load clients.\n");
    exit(1);
}

$migrated = 0;
$scanned = 0;
foreach ($clientsSnap['data'] as $clientId => $client) {
    if (!is_array($client) || !is_array($client['admins'] ?? null)) continue;
    foreach ($client['admins'] as $adminKey => $admin) {
        $scanned++;
        if (!is_array($admin)) continue;
        $email = strtolower(trim((string) ($admin['email'] ?? '')));
        if ($email === '') continue;
        if (preg_match('/^[A-Za-z0-9_-]{20,40}$/', (string) $adminKey)) continue; // looks like UID already
        $uid = lookup_uid_by_email($email, $webKey);
        if (!$uid) continue;
        $patch = firebase_rtdb_patch($dbUrl, 'clients/' . $clientId . '/admins', $access, [
            $uid => [
                'email' => $email,
                'role' => isset($admin['role']) ? (string) $admin['role'] : 'owner',
                'migratedAt' => time() * 1000
            ]
        ]);
        if (!isset($patch['error'])) $migrated++;
    }
}

echo "Scanned legacy admin rows: {$scanned}\n";
echo "Migrated rows: {$migrated}\n";
echo "Note: unresolved users are handled by login-time api/auth-recover-compat.php migration.\n";
