<?php

namespace App\Security\Voter;

use App\Dto\Output\OrganizationalUnitOutput;
use App\Entity\Client;
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 ClientVoter extends Voter
{
    public const string VIEW = 'CLIENT_VIEW';

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

    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 === 'CLIENT_VIEW') {
            foreach ($user->getAllowedOrganizationalUnits() as $allowedOrganizationalUnit) {
                if ($allowedOrganizationalUnit->getId() === $subject->getOrganizationalUnit()->getEntity()->getId()) {
                    return true;
                }
            }
        }

        return false;
    }
}
