<?php

namespace App\Security\Voter;

use App\Entity\Slot;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
use Symfony\Component\Security\Core\User\UserInterface;

class SlotAccessVoter extends Voter
{
    public const ACCESS_SLOT = 'ACCESS_SLOT';

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

    protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
    {
        $user = $token->getUser();

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

        $roles = $user->getRoles();

        // Accès immédiat pour ADMIN ou MANAGER
        if (in_array('ROLE_ADMIN', $roles, true) || in_array('ROLE_MANAGER', $roles, true)) {
            return true;
        }

        // Vérifie les droits pour ROLE_STAFF
        if (in_array('ROLE_STAFF', $roles, true)) {
            $gamemaster = $user->getLinkToGamemaster();

            if (!$gamemaster) {
                return false;
            }

            $event = $subject->getEvent();
            if (!$event) {
                return false;
            }

            $assignedGamemasters = $event->getGamemasterAssigned();

            return in_array($gamemaster, $assignedGamemasters->toArray(), true);
        }

        // ❌ Aucun autre rôle n'est autorisé
        return false;
    }
}