<?php

namespace BookneticApp\Providers\FSCode\Clients;

use BookneticApp\Providers\Helpers\Helper;
use BookneticVendor\GuzzleHttp\Client;
use BookneticVendor\GuzzleHttp\Exception\GuzzleException;

class FSCodeAPIClient
{
    private static string $baseUri = 'https://api.fs-code.com/v2/booknetic/';

    private Client $client;

    public function __construct()
    {
        $this->client = new Client([
            'verify'   => false,
            'base_uri' => self::$baseUri,
            'headers'  => [
                'Authorization' => 'Bearer ' . Helper::getOption('access_token', '', false),
                'Product'       => 'Booknetic ' . Helper::getInstalledVersion(),
                'Content-Type'  => 'application/json',
            ],
        ]);
    }

    public function get(string $path, array $body = []): array
    {
        return $this->request('get', $path, $body);
    }

    public function post(string $path, array $body = []): array
    {
        return $this->request('post', $path, $body);
    }

    public function request(string $method, string $path, array $body = []): array
    {
        try {
            $response = $this->client->request($method, $path, [ 'body' => json_encode($body) ]);
        } catch (GuzzleException $e) {
            return [];
        }

        if ($response->getStatusCode() !== 200) {
            return [];
        }

        $body = $response->getBody()->getContents();

        if (! $body) {
            return [];
        }

        return json_decode($body, true) ?: [];
    }

    public static function uploadFileFromName(string $name, string $dst): void
    {
        $url = sprintf('%s/%s', self::$baseUri, $name);

        self::uploadFileFromUrl($url, $dst);
    }

    public static function uploadFileFromUrl(string $src, string $dst): void
    {
        $img = file_get_contents($src);

        file_put_contents($dst, $img);
    }
}
