<?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\CoreBundle\Settings;

use Doctrine\ORM\EntityManagerInterface;
use Ferienpass\CoreBundle\Entity\PageConfig;
use Psr\Cache\CacheItemPoolInterface;

class PageConfigManager
{
    private const CACHE_KEY_PAGE_CONFIG = 'ferienpass.page_config';

    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly CacheItemPoolInterface $appConfigCache,
    ) {
    }

    public function getPageConfig(): PageConfig
    {
        $item = $this->appConfigCache->getItem(self::CACHE_KEY_PAGE_CONFIG);
        if ($item->isHit()) {
            return $item->get();
        }

        $config = $this->entityManager->getRepository(PageConfig::class)->findOneBy([]) ?? new PageConfig();

        $item->set($config);
        $this->appConfigCache->save($item);

        return $config;
    }

    public function savePageConfig(PageConfig $config): void
    {
        $this->entityManager->persist($config);
        $this->entityManager->flush();

        $this->appConfigCache->deleteItem(self::CACHE_KEY_PAGE_CONFIG);
    }
}
