<?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 les droits à l'image.
 *
 * Règles d'accès :
 * - ADMIN et SUPER_ADMIN : accès complet (lecture + modification)
 * - PROF, VIE_SCOLAIRE, SECRETARIAT : lecture seule
 *
 * @extends Voter<string, null>
 */
final class ImageRightsVoter extends Voter
{
    public const string VIEW = 'IMAGE_RIGHTS_VIEW';
    public const string EDIT = 'IMAGE_RIGHTS_EDIT';

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

    #[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::EDIT => $this->canEdit($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 canEdit(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;
    }
}
