<?php

declare(strict_types=1);

namespace External\PompoBundle\Util\AutomaticImport\KnizniWeb;

use External\PompoBundle\Exception\PompoException;
use KupShop\KupShopBundle\Util\System\CurlUtil;
use Symfony\Component\HttpClient\CurlHttpClient;

class KnizniWebAPI
{
    private const API_BASE_URL = 'https://vo.knizniweb.cz/b2bGate/v2';

    private ?CurlHttpClient $client = null;

    public function __construct(
        private readonly CurlUtil $curlUtil,
    ) {
    }

    public function getFeedZipFile(string $token): ?array
    {
        return $this->request(['token' => $token]) ?? null;
    }

    public function requestNewFeed(KnizniWebTypeEnum $type): array
    {
        return $this->request(['synctype' => $type->value]);
    }

    private function request(array $params): array
    {
        $response = $this->getClient()->request(
            'GET',
            $this->getAPIUrl($params)
        );

        if ($response->getStatusCode() >= 400) {
            throw new PompoException('KnizniWeb: api request failure!', null, [
                'statusCode' => $response->getStatusCode(),
                'data' => $response->getContent(false),
            ], $response->getStatusCode());
        }

        return json_decode($response->getContent() ?: '', true) ?: [];
    }

    private function getAPIUrl(array $params): string
    {
        return self::API_BASE_URL.'?'.http_build_query(array_merge($this->getCredentials(), $params));
    }

    private function getCredentials(): array
    {
        return [
            'login' => 'jakub.sula@pompo.cz',
            'password' => 'Pompo@123',
        ];
    }

    private function getClient(): CurlHttpClient
    {
        if (!$this->client) {
            $this->client = $this->curlUtil->getClient();
        }

        return $this->client;
    }
}
