<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Security;

use Chill\MainBundle\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Security;

/**
 * Security helper for Chill user.
 *
 * Provides security-related functionality such as user retrieval, authorization checks,
 * and token retrieval, in a context where only an authenticated @see{User::class} is expected.
 */
final readonly class ChillSecurity implements AuthorizationCheckerInterface
{
    public function __construct(private Security $security) {}

    public function hasUser(): bool
    {
        return null !== $this->security->getUser();
    }

    public function getUser(): User
    {
        $user = $this->security->getUser();

        if (!$user instanceof User) {
            throw new \LogicException(sprintf('authenticated user should be an instance of %s, %s given', User::class, null !== $user ? $user::class : self::class));
        }

        return $user;
    }

    public function isGranted($attribute, $subject = null): bool
    {
        return $this->security->isGranted($attribute, $subject);
    }

    public function getToken(): ?TokenInterface
    {
        return $this->security->getToken();
    }
}
