<?php

declare(strict_types=1);

namespace Gls\GlsPoland\DataProvider;

use Gls\GlsPoland\AdePlus\ParcelShop\ClientInterface;
use Gls\GlsPoland\AdePlus\ParcelShop\Fault\ParcelShopNotFoundFault;
use Gls\GlsPoland\AdePlus\ParcelShop\ParcelShop;
use Psr\Cache\CacheItemPoolInterface;

final class ParcelShopDataProvider
{
    private $cache;
    private $client;

    public function __construct(CacheItemPoolInterface $cache, ClientInterface $client)
    {
        $this->cache = $cache;
        $this->client = $client;
    }

    public function getParcelShop(string $id): ?ParcelShop
    {
        $item = $this->cache->getItem('gls_poland_parcel_shop_' . $id);

        if ($item->isHit()) {
            return $item->get();
        }

        try {
            $parcelShop = $this->client->getParcelShop($id);
        } catch (ParcelShopNotFoundFault $e) {
            $parcelShop = null;
        }

        $item->set($parcelShop);
        $item->expiresAfter(new \DateInterval('P1D'));

        $this->cache->save($item);

        return $parcelShop;
    }
}
