<?php

declare(strict_types=1);

function bitrixCallRaw(string $method, array $params = []): array
{
    if (!class_exists('CRest')) {
        throw new RuntimeException('CRest is not loaded.');
    }

    $response = CRest::call($method, $params);

    return is_array($response) ? $response : ['result' => $response];
}

function bitrixCall(string $method, array $params = []): array
{
    $response = bitrixCallRaw($method, $params);
    if (isset($response['error'])) {
        throw new RuntimeException(sprintf(
            'Bitrix REST error in %s: %s - %s',
            $method,
            (string) $response['error'],
            (string) ($response['error_description'] ?? $response['error_information'] ?? '')
        ));
    }

    return $response;
}

function installCrestApp(): array
{
    if (!class_exists('CRest')) {
        throw new RuntimeException('CRest is not loaded.');
    }

    $response = CRest::installApp();

    return is_array($response) ? $response : ['result' => $response];
}
