<?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\PickupOrder\Util;

use InPost\International\Api\Exception\ApiClientExceptionInterface;
use InPost\International\Api\Pickup\PickupsApiClientInterface;
use InPost\International\Api\Pickup\Request\CutoffTimeRequest;
use InPost\International\Entity\PickupAddress;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Clock\ClockInterface;

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

class CutoffPickupTimeChecker
{
    /**
     * @var CacheItemPoolInterface
     */
    private $cache;

    /**
     * @var PickupsApiClientInterface
     */
    private $client;

    /**
     * @var ClockInterface
     */
    private $clock;

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

    public function check(PickupAddress $address): ?\DateTimeImmutable
    {
        if (null === $time = $this->getCutoffTime($address)) {
            return null;
        }

        if (false !== $timezone = $this->clock->now()->getTimezone()) {
            $time = $time->setTimezone($timezone);
        }

        return $time;
    }

    private function getCutoffTime(PickupAddress $address): ?\DateTimeImmutable
    {
        $country = $address->getAddress()->getCountry();
        $postcode = $address->getAddress()->getPostcode();

        $key = sprintf('cutoff_pickup_time_%s_%s', $country->value, $postcode);

        $item = $this->cache->getItem($key);

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

        try {
            $value = $this->client->getCutoffPickupTime(new CutoffTimeRequest($country, $postcode))->getCutoffTime();
        } catch (ApiClientExceptionInterface $e) {
            return null;
        }

        $item->set($value);
        $item->expiresAfter(new \DateInterval('P1D'));
        $this->cache->save($item);

        return $value;
    }
}
