<?php

namespace App\Service\SnipParser\Twig;

use App\Entity\Snip;
use App\Repository\SnipRepository;
use App\Security\Voter\SnipVoter;
use App\Service\SnipContent\SnipContentService;
use Symfony\Bundle\SecurityBundle\Security;
use Twig\Error\LoaderError;
use Twig\Loader\LoaderInterface;
use Twig\Source;

class SnipLoader implements LoaderInterface
{
    public function __construct(
        private readonly SnipRepository     $repository,
        private readonly Security           $security,
    ) {}

    public function getSourceContext(string $name): Source
    {
        return new Source($this->getFromKey($name)->getActiveText(), $name);
    }

    public function getCacheKey(string $name): string
    {
        return $this->getFromKey($name)->activeVersion->id;
    }

    public function isFresh(string $name, int $time): bool
    {
        $this->getFromKey($name);

        return true;
    }

    public function exists(string $name): bool
    {
        try {
            $this->getFromKey($name);
        } catch (LoaderError) {
            return false;
        }

        return true;
    }

    private function getFromKey(string $key): Snip
    {
        $snip = $this->repository->find($key);
        if (!$snip) {
            throw new LoaderError(\sprintf('Template "%s" is not defined.', $key));
        }
        if (!$this->security->isGranted(SnipVoter::VIEW, $snip)) {
            throw new LoaderError(\sprintf('You do not have permission to view the template "%s".', $key));
        }

        return $snip;
    }
}
