<?php declare(strict_types=1);

namespace Newland\Toubiz\Weather\Neos\Controller;

use Neos\Cache\Frontend\FrontendInterface as CacheFrontend;
use Neos\Flow\Cache\CacheManager;
use Newland\NeosCommon\Controller\AbstractApiController;
use Newland\NeosCommon\Controller\HttpException;
use Newland\Toubiz\Sync\Neos\Domain\Repository\WeatherRepository;
use Neos\Flow\Annotations as Flow;
use function Safe\json_encode;

class ApiController extends AbstractApiController
{
    private const MINUTE = 1 / 60;
    protected $browserCacheLifetimeHours = 10 * self::MINUTE;

    /**
     * @var WeatherRepository
     * @Flow\Inject()
     */
    protected $weatherRepository;

    /** @var CacheFrontend */
    protected $cache;
    public function injectCache(CacheManager $cacheManager): void
    {
        $this->cache = $cacheManager->getCache('Newland_Toubiz_Weather_Neos_ApiResponse');
    }


    public function weatherAction(string $originalId): string
    {
        if ($this->cache->has($originalId)) {
            $json = $this->cache->get($originalId);
        } else {
            $weather = $this->weatherRepository->findOneByOriginalId($originalId);
            if (!$weather) {
                throw new HttpException('Could not find weather', 404);
            }

            $json = json_encode($weather);
            $this->cache->set($originalId, $json);
        }

        return $json;
    }
}
