<?php

declare(strict_types=1);

namespace App\Module\Core\Infrastructure\ApiPlatform\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\Pagination\Pagination;
use ApiPlatform\State\Pagination\TraversablePaginator;
use ApiPlatform\State\ProviderInterface;
use App\Module\Core\Domain\Entity\Notification;
use App\Module\Core\Infrastructure\Doctrine\DoctrineNotificationRepository;
use ArrayIterator;
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
use Symfony\Bundle\SecurityBundle\Security;

use function count;

/**
 * @implements ProviderInterface<Notification>
 */
final readonly class NotificationProvider implements ProviderInterface
{
    public function __construct(
        private Security $security,
        private DoctrineNotificationRepository $notificationRepository,
        private Pagination $pagination,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object
    {
        $user = $this->security->getUser();

        [$page, $offset, $limit] = $this->pagination->getPagination($operation, $context);

        $queryBuilder = $this->notificationRepository
            ->createUserNotificationsQueryBuilder($user)
            ->setFirstResult($offset)
            ->setMaxResults($limit)
        ;

        $doctrinePaginator = new DoctrinePaginator($queryBuilder);

        return new TraversablePaginator(
            new ArrayIterator(iterator_to_array($doctrinePaginator, false)),
            $page,
            $limit,
            (float) count($doctrinePaginator),
        );
    }
}
