<?php
declare(strict_types=1);

namespace App\Security\Voter;

use App\Service\Security\InternalRequestsService;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

/**
 * @package App\Security
 */
class InternalRequestsVoter extends Voter
{
    public function __construct(
        private readonly InternalRequestsService $internalRequestsService,
        protected RequestStack $requestStack,
    )
    {}

    /**
     * @param string $attribute
     * @param mixed $subject
     * @return bool
     */
    protected function supports(string $attribute, mixed $subject): bool
    {
        return $attribute === 'INTERNAL_REQUEST';
    }

    /**
     * @param string $attribute
     * @param mixed $subject
     * @param TokenInterface $token
     * @return bool
     */
    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
    {
        return $this->isValidInternalRequest();
    }

    /**
     * Is the current request a valid internal request ?
     *
     * @return bool
     */
    protected function isValidInternalRequest(): bool {
        $request = $this->requestStack->getCurrentRequest();

        $clientIp = $request->server->get('REMOTE_ADDR');
        $internalRequestsToken = $request->headers->get('internal-requests-token')?? null;

        return $internalRequestsToken && $this->internalRequestsService->isAllowed($clientIp, $internalRequestsToken);
    }
}
