<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Query\GetUsers\GetUsersHandler;
use App\Administration\Application\Query\GetUsers\GetUsersQuery;
use App\Administration\Infrastructure\Api\Resource\UserResource;
use App\Administration\Infrastructure\Security\UserVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

use Override;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * State Provider pour récupérer la liste des utilisateurs avec filtres.
 *
 * @implements ProviderInterface<UserResource>
 */
final readonly class UserCollectionProvider implements ProviderInterface
{
    public function __construct(
        private GetUsersHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

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

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

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();
        /** @var array<string, string> $filters */
        $filters = $context['filters'] ?? [];

        $query = new GetUsersQuery(
            tenantId: $tenantId,
            role: isset($filters['role']) ? (string) $filters['role'] : null,
            statut: isset($filters['statut']) ? (string) $filters['statut'] : null,
        );

        $userDtos = ($this->handler)($query);

        return array_map(UserResource::fromDto(...), $userDtos);
    }
}
