<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Controller;

use Neos\ContentRepository\Domain\Model\Node;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\ContentRepository\Domain\Service\Context;
use Neos\ContentRepository\Domain\Service\ContextFactory;
use Neos\ContentRepository\Domain\Service\ContextFactoryInterface;
use Neos\Flow\Mvc\Controller\ActionController;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Utility\Now;
use Neos\Neos\Domain\Service\ContentContext;
use Newland\NeosCommon\Service\ControllerContextFactory;
use Newland\Toubiz\Sync\Neos\Service\Cache\CacheServiceInterface;

class CacheController extends ActionController
{
    /**
     * @var ContextFactoryInterface
     * @Flow\Inject()
     */
    protected $contextFactory;

    /**
     * @var CacheServiceInterface
     * @Flow\Inject()
     */
    protected $cacheService;

    public function clearPageCacheAction(Node $node): array
    {
        $uri = $this->getLiveUri($node);
        $this->cacheService->flushUri($uri);

        return [ 'message' => 'Cache cleared' ];
    }

    protected function getLiveUri(Node $node): string
    {
        $liveContext = $this->getLiveContext($node);
        $liveNode = $liveContext->getNodeByIdentifier((string) $node->getNodeAggregateIdentifier());

        return $this->uriBuilder
            ->reset()
            ->setCreateAbsoluteUri(true)
            ->uriFor('show', [ 'node' => $liveNode ], 'Frontend\Node', 'Neos.Neos');
    }

    public function getLiveContext(NodeInterface $node): Context
    {
        return $this->contextFactory->create([
            'workspaceName' => 'live',
            'currentDateTime' => new Now(),
            'dimensions' => $node->getDimensions(),
            'targetDimensions' => [],
            'invisibleContentShown' => false,
            'removedContentShown' => false,
            'inaccessibleContentShown' => false,
        ]);
    }
}
