<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Security;

use App\Administration\Domain\Model\User\Role;

use function in_array;

use Override;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * Voter pour les autorisations sur le branding établissement.
 *
 * Règles d'accès :
 * - ADMIN et SUPER_ADMIN : accès complet (lecture + configuration)
 * - PROF, VIE_SCOLAIRE, SECRETARIAT : lecture seule
 *
 * @extends Voter<string, null>
 */
final class SchoolBrandingVoter extends Voter
{
    public const string VIEW = 'BRANDING_VIEW';
    public const string CONFIGURE = 'BRANDING_CONFIGURE';

    private const array SUPPORTED_ATTRIBUTES = [
        self::VIEW,
        self::CONFIGURE,
    ];

    #[Override]
    protected function supports(string $attribute, mixed $subject): bool
    {
        return in_array($attribute, self::SUPPORTED_ATTRIBUTES, true);
    }

    #[Override]
    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool
    {
        $user = $token->getUser();

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

        $roles = $user->getRoles();

        return match ($attribute) {
            self::VIEW => $this->canView($roles),
            self::CONFIGURE => $this->canConfigure($roles),
            default => false,
        };
    }

    /**
     * @param string[] $roles
     */
    private function canView(array $roles): bool
    {
        return $this->hasAnyRole($roles, [
            Role::SUPER_ADMIN->value,
            Role::ADMIN->value,
            Role::PROF->value,
            Role::VIE_SCOLAIRE->value,
            Role::SECRETARIAT->value,
        ]);
    }

    /**
     * @param string[] $roles
     */
    private function canConfigure(array $roles): bool
    {
        return $this->hasAnyRole($roles, [
            Role::SUPER_ADMIN->value,
            Role::ADMIN->value,
        ]);
    }

    /**
     * @param string[] $userRoles
     * @param string[] $allowedRoles
     */
    private function hasAnyRole(array $userRoles, array $allowedRoles): bool
    {
        foreach ($userRoles as $role) {
            if (in_array($role, $allowedRoles, true)) {
                return true;
            }
        }

        return false;
    }
}
