<?php
/**
 * Copyright since 2025 InPost S.A.
 *
 * For the full license information, please view the LICENSE file bundled with the module.
 *
 * @author InPost S.A.
 * @copyright since 2025 InPost S.A.
 * @license MIT
 */

declare(strict_types=1);

namespace InPost\International\Geocoding;

use InPost\International\Api\Point\Model\Coordinates;
use InPost\International\Delivery\Address;
use Psr\Cache\CacheItemPoolInterface;

if (!defined('_PS_VERSION_')) {
    exit;
}

final class CachingGeocoder implements GeocoderInterface
{
    /**
     * @var GeocoderInterface
     */
    private $geocoder;

    /**
     * @var CacheItemPoolInterface
     */
    private $cache;

    /**
     * @var int|null
     */
    private $ttl;

    public function __construct(GeocoderInterface $geocoder, CacheItemPoolInterface $cache, int $ttl = null)
    {
        $this->geocoder = $geocoder;
        $this->cache = $cache;
        $this->ttl = $ttl;
    }

    public function geocode(Address $address): ?Coordinates
    {
        $key = $this->getCacheKey($address);
        $item = $this->cache->getItem($key);

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

        $coordinates = $this->geocoder->geocode($address);

        $item->set($coordinates);
        $item->expiresAfter($this->ttl);
        $this->cache->save($item);

        return $coordinates;
    }

    private function getCacheKey(Address $address): string
    {
        return sprintf('%s_%s', $address->getCountry()->value, hash('sha1', (string) $address));
    }
}
