<?php

namespace App\Library\VK;

use Exception;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;

final class VkApiClient
{
    public function __construct(
        protected ClientInterface $http,
        protected string $token,
        protected string $url,
        protected string $version = '5.131'
    ) {}

    /**
     * @throws GuzzleException
     */
    public function call(
        string $method,
        array $params = []
    ): array {
        $response = $this->http->request('POST', "{$this->url}/{$method}", [
                'form_params' => array_merge($params, [
                'access_token' => $this->token,
                'v' => $this->version,
            ]),
        ]);

        $result = json_decode($response->getBody()->getContents(), true);

        if (isset($result['error'])) {
            $message = "VK API Error: " . $result['error']['error_msg'];
            Log::error($message);
            throw new Exception($message);
        }

        return $result;
    }
}
