<?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\GetStudentsWithClass\GetStudentsWithClassHandler;
use App\Administration\Application\Query\GetStudentsWithClass\GetStudentsWithClassQuery;
use App\Administration\Infrastructure\Api\Resource\StudentResource;
use App\Administration\Infrastructure\Security\StudentVoter;
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\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;

/**
 * @implements ProviderInterface<StudentResource>
 */
final readonly class StudentCollectionProvider implements ProviderInterface
{
    public function __construct(
        private GetStudentsWithClassHandler $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(StudentVoter::VIEW)) {
            throw new AccessDeniedHttpException('Vous n\'êtes pas autorisé à consulter les élèves.');
        }

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

        $tenantId = (string) $this->tenantContext->getCurrentTenantId();
        $academicYearId = $this->academicYearResolver->resolve('current')
            ?? throw new BadRequestHttpException('Impossible de résoudre l\'année scolaire courante.');

        /** @var array<string, mixed> $filters */
        $filters = $context['filters'] ?? [];
        /** @var int|string $rawPage */
        $rawPage = $filters['page'] ?? 1;
        $page = (int) $rawPage;
        /** @var int|string $rawItemsPerPage */
        $rawItemsPerPage = $filters['itemsPerPage'] ?? 30;
        $itemsPerPage = (int) $rawItemsPerPage;
        /** @var string|null $search */
        $search = isset($filters['search']) ? $filters['search'] : null;
        /** @var string|null $classId */
        $classId = isset($filters['classId']) ? $filters['classId'] : null;

        $result = ($this->handler)(new GetStudentsWithClassQuery(
            tenantId: $tenantId,
            academicYearId: $academicYearId,
            classId: $classId,
            page: $page,
            limit: $itemsPerPage,
            search: $search,
        ));

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

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