<?php

namespace App\Security\Voter;

use App\Dto\Output\OrganizationalUnitOutput;
use App\Entity\OrganizationalUnit;
use App\Entity\User;
use App\Model\UserGroupPermissions;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;

class OrganizationalUnitVoter extends Voter
{
    public const string VIEW = 'ORGANIZATIONAL_UNIT_VIEW';

    protected function supports(string $attribute, mixed $subject): bool
    {
        return $attribute === self::VIEW
            && $subject instanceof OrganizationalUnitOutput;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
    {
        /** @var User $user */
        $user = $token->getUser();


        if (!$user instanceof UserInterface) {
            return false;
        }

        if (in_array(UserGroupPermissions::ROLE_SUPER_ADMIN, $user->getRoles())) {
            return true;
        }

        if ($attribute === 'ORGANIZATIONAL_UNIT_VIEW' ) {
            foreach ($user->getAllowedOrganizationalUnits() as $allowedOrganizationalUnit) {
                if ($allowedOrganizationalUnit->getId() === $subject->getEntity()->getId()) {
                    return true;
                }
            }
        }

        return false;
    }
}
