<?php
require_once __DIR__ . '/_super_admin_common.php';

$body = sa_require_post_json();
[$uid, $email, $dbUrl, $accessToken, $cfg] = sa_require_super_admin_session_with_db();

$clientId = trim((string)($body['clientId'] ?? ''));
if ($clientId === '') sa_json_response(400, ['status' => 'error', 'message' => 'clientId required']);

$token = 'imp_' . bin2hex(random_bytes(18));
$ttl = (int)($cfg['impersonation_ttl_seconds'] ?? 900);
$expiresAt = time() + max(60, $ttl);

$save = firebase_rtdb_put($dbUrl, 'superAdminImpersonation/' . $token, $accessToken, [
    'clientId' => $clientId,
    'createdByUid' => $uid,
    'createdByEmail' => $email,
    'createdAt' => time() * 1000,
    'expiresAt' => $expiresAt * 1000,
    'used' => false,
]);
if (isset($save['error'])) sa_json_response(500, ['status' => 'error', 'message' => 'Could not create impersonation token']);

sa_audit_log($dbUrl, $accessToken, $uid, $email, 'create_impersonation_token', $clientId, ['expiresAt' => $expiresAt * 1000]);
sa_json_response(200, [
    'status' => 'success',
    'token' => $token,
    'clientId' => $clientId,
    'expiresAt' => $expiresAt * 1000
]);
