<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Domain\Exception\UserNotFoundException;
use App\Administration\Domain\Model\User\UserId;
use App\Administration\Domain\Repository\UserRepository;
use App\Administration\Infrastructure\Api\Resource\UserResource;
use App\Administration\Infrastructure\Security\UserVoter;
use App\Shared\Domain\Clock;
use App\Shared\Infrastructure\Tenant\TenantContext;
use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * State Provider pour récupérer un utilisateur par ID.
 *
 * @implements ProviderInterface<UserResource>
 */
final readonly class UserItemProvider implements ProviderInterface
{
    public function __construct(
        private UserRepository $userRepository,
        private AuthorizationCheckerInterface $authorizationChecker,
        private TenantContext $tenantContext,
        private Clock $clock,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): UserResource
    {
        if (!$this->authorizationChecker->isGranted(UserVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à voir cet utilisateur.');
        }

        if (!$this->tenantContext->hasTenant()) {
            throw new UnauthorizedHttpException('Bearer', 'Tenant non défini.');
        }

        /** @var string $userId */
        $userId = $uriVariables['id'] ?? '';

        try {
            $user = $this->userRepository->get(UserId::fromString($userId));
        } catch (UserNotFoundException $e) {
            throw new NotFoundHttpException($e->getMessage());
        }

        if (!$user->tenantId->equals($this->tenantContext->getCurrentTenantId())) {
            throw new NotFoundHttpException('User not found.');
        }

        return UserResource::fromDomain($user, $this->clock->now());
    }
}
