<?php declare(strict_types=1);

namespace App\Engine\VisitorsNotification;

final readonly class VisitorsNotificationsProvider
{

    public const CACHE_TTL = 3600;
    public const CACHE_KEY_PREFIX = "VisitorsNotificationPrefix_";

    public function __construct(
        private VisitorsNotificationRepository          $visitorsNotificationRepository,
        private \Symfony\Contracts\Cache\CacheInterface $fileAdapterCache,
    ) {
    }

    public static function getCacheKey(LocationEnum $location): string
    {
        return self::CACHE_KEY_PREFIX . $location->value;
    }

    /**
     * @return array<\App\Engine\VisitorsNotification\VisitorsNotificationViewModel>
     */
    public function provideForLocationCached(LocationEnum $location): array
    {
        return $this->fileAdapterCache->get(self::getCacheKey($location), function (\Symfony\Component\Cache\CacheItem $item) use ($location) {
            $item->expiresAfter(self::CACHE_TTL);
            return $this->provideForLocation($location);
        });
    }

    /**
     * @return array<\App\Engine\VisitorsNotification\VisitorsNotificationViewModel>
     */
    public function provideForLocation(LocationEnum $location): array
    {
        $cb = $this->visitorsNotificationRepository->createQueryBuilder("vN");
        $loadedResults = $cb->where("vN.enabled = 1")
            ->andWhere('vN.location IN (:location)')
            ->setParameter("location", [LocationEnum::Everywhere, $location])
            ->orderBy("vN.priority", "ASC")
            ->getQuery()
            ->getResult();

        $results = [];
        foreach ($loadedResults as $loadedResult) {
            $results[] = new VisitorsNotificationViewModel(
                id: $loadedResult->getId(),
                priority: $loadedResult->getPriority(),
                title: $loadedResult->getTitle(),
                text: $loadedResult->getText(),
                type: $loadedResult->getType()->value,
            );
        }

        return $results;
    }

}