<?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\GetAllAssignments\AssignmentWithNamesDto;
use App\Administration\Application\Query\GetAllAssignments\GetAllAssignmentsHandler;
use App\Administration\Application\Query\GetAllAssignments\GetAllAssignmentsQuery;
use App\Administration\Infrastructure\Api\Resource\TeacherAssignmentResource;
use App\Administration\Infrastructure\Security\TeacherAssignmentVoter;
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;

/**
 * State Provider pour récupérer toutes les affectations avec pagination et recherche.
 *
 * @implements ProviderInterface<TeacherAssignmentResource>
 */
final readonly class TeacherAssignmentsCollectionProvider implements ProviderInterface
{
    public function __construct(
        private GetAllAssignmentsHandler $handler,
        private TenantContext $tenantContext,
        private AuthorizationCheckerInterface $authorizationChecker,
    ) {
    }

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

        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 GetAllAssignmentsQuery(
            tenantId: $tenantId,
            page: $page,
            limit: $itemsPerPage,
            search: isset($filters['search']) ? (string) $filters['search'] : null,
        );

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

        $resources = array_map(
            static function (AssignmentWithNamesDto $dto) {
                $resource = new TeacherAssignmentResource();
                $resource->id = $dto->id;
                $resource->teacherId = $dto->teacherId;
                $resource->classId = $dto->classId;
                $resource->subjectId = $dto->subjectId;
                $resource->academicYearId = $dto->academicYearId;
                $resource->status = $dto->status;
                $resource->startDate = $dto->startDate;
                $resource->endDate = $dto->endDate;
                $resource->createdAt = $dto->createdAt;
                $resource->teacherFirstName = $dto->teacherFirstName;
                $resource->teacherLastName = $dto->teacherLastName;
                $resource->className = $dto->className;
                $resource->subjectName = $dto->subjectName;

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

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