<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Security;

use App\Administration\Domain\Model\User\Role;
use App\Administration\Infrastructure\Api\Resource\ParentInvitationResource;

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 la gestion des invitations parents.
 *
 * Seuls ADMIN et SUPER_ADMIN peuvent gérer les invitations parents.
 *
 * @extends Voter<string, ParentInvitationResource|null>
 */
final class ParentInvitationVoter extends Voter
{
    public const string VIEW = 'PARENT_INVITATION_VIEW';
    public const string CREATE = 'PARENT_INVITATION_CREATE';
    public const string RESEND = 'PARENT_INVITATION_RESEND';

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

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

        if ($subject === null) {
            return true;
        }

        return $subject instanceof ParentInvitationResource;
    }

    #[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::CREATE, self::RESEND => $this->canManage($roles),
            default => false,
        };
    }

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

    /**
     * @param string[] $roles
     */
    private function canManage(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;
    }
}
