<?php
/**
 * POST JSON: { idToken, clientId }
 * Returns admins map (uid -> safe fields). Store owners only.
 */
require_once __DIR__ . '/tenant-admin-common.php';

$body = tenant_admin_require_post_json();
$clientId = tenant_admin_require_client_id($body);
$idToken = isset($body['idToken']) ? trim((string) $body['idToken']) : '';

$ctx = tenant_admin_require_bootstrap();
$dbUrl = $ctx['dbUrl'];
$accessToken = $ctx['accessToken'];
$webKey = $ctx['webKey'];

$actor = tenant_admin_lookup_id_token($idToken, $webKey);
$actorNode = tenant_admin_get_admin_node($dbUrl, $accessToken, $clientId, $actor['uid']);
if (!tenant_admin_is_store_owner($actorNode)) {
    tenant_admin_json_response(403, ['status' => 'error', 'message' => 'Only the store owner can view the admin team.']);
}

$snap = firebase_rtdb_get($dbUrl, 'clients/' . $clientId . '/admins', $accessToken);
if (isset($snap['error'])) {
    tenant_admin_json_response(500, ['status' => 'error', 'message' => 'RTDB read failed: ' . $snap['error']]);
}
$raw = $snap['data'] ?? null;
$out = [];
if (is_array($raw)) {
    foreach ($raw as $uid => $node) {
        if (!is_string($uid) || $uid === '' || !is_array($node)) {
            continue;
        }
        $role = isset($node['role']) && (string) $node['role'] !== '' ? (string) $node['role'] : 'owner';
        $out[$uid] = [
            'email' => isset($node['email']) ? (string) $node['email'] : '',
            'role' => $role,
            'permissions' => isset($node['permissions']) && is_array($node['permissions']) ? $node['permissions'] : null,
        ];
    }
}

tenant_admin_json_response(200, ['status' => 'success', 'admins' => $out]);
