<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\AdminBundle\Cache;

use Ferienpass\AdminBundle\Form\Filter\Ttl;
use Ferienpass\CoreBundle\Settings\PageConfigManager;

final class FilteredPageTtlCalculator
{
    public function __construct(private readonly PageConfigManager $pageConfigManager)
    {
    }

    public function secondsUntilNextReset(Ttl $ttl): int
    {
        $tz = $this->adminTimezone();
        $now = new \DateTimeImmutable('now', $tz);
        $next = match ($ttl) {
            Ttl::EndOfDay => $now->modify('tomorrow midnight'),
            Ttl::TopOfHour => $now
                ->modify('+1 hour')
                ->setTime((int) $now->modify('+1 hour')->format('H'), 0, 0),
        };

        return max(0, $next->getTimestamp() - $now->getTimestamp());
    }

    private function adminTimezone(): \DateTimeZone
    {
        $tz = $this->pageConfigManager->getPageConfig()->getTimezone();

        return new \DateTimeZone('' !== $tz ? $tz : date_default_timezone_get());
    }
}
