<?php

declare(strict_types=1);

namespace App\Security\Voter;

use App\Entity\Absence;
use App\Entity\User;
use App\Security\EmployeeScopeService;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Vote;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

final class AbsenceVoter extends Voter
{
    public const string VIEW = 'ABSENCE_VIEW';
    public const string EDIT = 'ABSENCE_EDIT';

    public function __construct(
        private readonly Security $security,
        private readonly EmployeeScopeService $employeeScopeService,
    ) {}

    protected function supports(string $attribute, mixed $subject): bool
    {
        return in_array($attribute, [self::VIEW, self::EDIT], true) && $subject instanceof Absence;
    }

    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token, ?Vote $vote = null): bool
    {
        $user = $this->security->getUser();
        if (!$user instanceof User) {
            return false;
        }

        if (!$subject instanceof Absence) {
            return false;
        }

        $employee = $subject->getEmployee();
        if (null === $employee) {
            return false;
        }

        return $this->employeeScopeService->canAccessEmployee($user, $employee);
    }
}
