<?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\GetClasses\GetClassesHandler;
use App\Administration\Application\Query\GetClasses\GetClassesQuery;
use App\Administration\Infrastructure\Api\Resource\ClassResource;
use App\Administration\Infrastructure\Security\ClassVoter;
use App\Administration\Infrastructure\Service\CurrentAcademicYearResolver;
use App\Shared\Infrastructure\Tenant\TenantContext;
use ArrayIterator;
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 classes avec pagination.
 *
 * @implements ProviderInterface<ClassResource>
 */
final readonly class ClassCollectionProvider implements ProviderInterface
{
    public function __construct(
        private GetClassesHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
        private CurrentAcademicYearResolver $academicYearResolver,
    ) {
    }

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

        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);

        $academicYearId = $this->academicYearResolver->resolve('current') ?? '';
        if ($academicYearId === '') {
            return new TraversablePaginator(new ArrayIterator([]), $page, $itemsPerPage, 0);
        }

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

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

        $resources = array_map(
            static function ($dto) {
                $resource = new ClassResource();
                $resource->id = $dto->id;
                $resource->name = $dto->name;
                $resource->level = $dto->level;
                $resource->capacity = $dto->capacity;
                $resource->description = $dto->description;
                $resource->status = $dto->status;
                $resource->createdAt = $dto->createdAt;
                $resource->updatedAt = $dto->updatedAt;

                return $resource;
            },
            $result->items,
        );

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