<?php

declare(strict_types=1);

namespace App\Administration\Infrastructure\Api\Provider;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\Pagination\TraversablePaginator;
use ApiPlatform\State\ProviderInterface;
use App\Administration\Application\Query\GetStudentsImageRights\GetStudentsImageRightsHandler;
use App\Administration\Application\Query\GetStudentsImageRights\GetStudentsImageRightsQuery;
use App\Administration\Infrastructure\Api\Resource\ImageRightsResource;
use App\Administration\Infrastructure\Security\ImageRightsVoter;
use App\Shared\Infrastructure\Tenant\TenantContext;

use function array_map;

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

/**
 * @implements ProviderInterface<ImageRightsResource>
 */
final readonly class ImageRightsCollectionProvider implements ProviderInterface
{
    public function __construct(
        private GetStudentsImageRightsHandler $handler,
        private AuthorizationCheckerInterface $authorizationChecker,
        private TenantContext $tenantContext,
    ) {
    }

    #[Override]
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): TraversablePaginator
    {
        if (!$this->authorizationChecker->isGranted(ImageRightsVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à consulter les droits à l\'image.');
        }

        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'] ?? [];

        $page = (int) ($filters['page'] ?? 1);
        $itemsPerPage = (int) ($filters['itemsPerPage'] ?? 30);

        $query = new GetStudentsImageRightsQuery(
            tenantId: $tenantId,
            status: isset($filters['status']) ? (string) $filters['status'] : null,
            page: $page,
            limit: $itemsPerPage,
            search: isset($filters['search']) ? (string) $filters['search'] : null,
        );

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

        $resources = array_map(ImageRightsResource::fromDto(...), $result->items);

        return new TraversablePaginator(
            new ArrayIterator($resources),
            $result->page,
            $result->limit,
            $result->total,
        );
    }
}
