<?php

declare(strict_types=1);

namespace App\Scolarite\Infrastructure\Security;

use App\Administration\Domain\Model\User\Role;
use App\Administration\Infrastructure\Security\SecurityUser;
use App\Scolarite\Domain\Model\TeacherReplacement\TeacherReplacement;

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;

/**
 * Voter pour les autorisations sur les remplacements enseignants.
 *
 * Règles d'accès :
 * - ADMIN et SUPER_ADMIN : accès complet (CRUD)
 * - ENSEIGNANT : lecture seule (ses propres remplacements actifs/passifs)
 * - Autres rôles : pas d'accès
 *
 * @extends Voter<string, TeacherReplacement|null>
 */
final class TeacherReplacementVoter extends Voter
{
    public const string VIEW = 'TEACHER_REPLACEMENT_VIEW';
    public const string CREATE = 'TEACHER_REPLACEMENT_CREATE';
    public const string DELETE = 'TEACHER_REPLACEMENT_DELETE';

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

    #[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 TeacherReplacement;
    }

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

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

        $roles = $user->getRoles();

        return match ($attribute) {
            self::VIEW => $this->canView($roles, $user, $subject),
            self::CREATE => $this->canCreate($roles),
            self::DELETE => $this->canDelete($roles),
            default => false,
        };
    }

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

        if ($this->hasAnyRole($roles, [Role::PROF->value])) {
            return $this->isInvolvedTeacher($user, $subject);
        }

        return false;
    }

    private function isInvolvedTeacher(SecurityUser $user, mixed $subject): bool
    {
        if (!$subject instanceof TeacherReplacement) {
            return false;
        }

        return (string) $subject->replacedTeacherId === $user->userId()
            || (string) $subject->replacementTeacherId === $user->userId();
    }

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

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