<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Api\Google;

use YOOtheme\Http\Response;
use ZOOlanders\YOOessentials\Api\AbstractApi;

abstract class AbstractGoogleApi extends AbstractApi
{
    protected string $key = '';

    protected string $token = '';

    public function withKey(string $key): self
    {
        $this->key = $key;
        $this->token = '';

        return $this;
    }

    public function withToken(string $token): self
    {
        $this->key = '';
        $this->token = $token;

        return $this;
    }

    protected function getHeaders(): array
    {
        $headers = parent::getHeaders();

        if ($this->token) {
            $headers = $headers + [
                'Authorization' => "Bearer {$this->token}",
            ];
        }

        return $headers;
    }

    public function get(string $name, array $args = []): array
    {
        if ($this->key) {
            $args['key'] = $this->key;
        }

        return $this->request('GET', $name, $args);
    }

    protected function processResponse(Response $response): array
    {
        $result = json_decode($response->getBody(), true);
        $success =
            $response->getStatusCode() >= 200 && $response->getStatusCode() <= 299 && ($result['success'] ?? '') !== false;

        if (!$success) {
            $code = $result['error']['code'] ?? ($response->getStatusCode() ?? 400);
            $message = $result['error']['message'] ?? ($response->getReasonPhrase() ?? 'Unknown Error');

            throw new \Exception($message, $code);
        }

        return $result;
    }
}
