<?php

declare(strict_types=1);

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

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Module\ProjectManagement\Domain\Entity\TaskDocument;
use App\Shared\Domain\Contract\UserInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;

/**
 * @implements ProviderInterface<TaskDocument>
 */
final readonly class TaskDocumentProvider implements ProviderInterface
{
    public function __construct(
        private EntityManagerInterface $entityManager,
        private Security $security,
    ) {}

    public function provide(Operation $operation, array $uriVariables = [], array $context = []): array|TaskDocument|null
    {
        $user = $this->security->getUser();
        assert($user instanceof UserInterface);

        $repo = $this->entityManager->getRepository(TaskDocument::class);

        // Single item
        if (isset($uriVariables['id'])) {
            return $repo->find($uriVariables['id']);
        }

        // Collection
        $qb = $repo->createQueryBuilder('d')
            ->orderBy('d.id', 'DESC')
        ;

        // Apply filters from query parameters
        $filters = $context['filters'] ?? [];
        if (isset($filters['task'])) {
            $qb->andWhere('d.task = :task')
                ->setParameter('task', self::extractId($filters['task']))
            ;
        }

        return $qb->getQuery()->getResult();
    }

    private static function extractId(string $value): int
    {
        return is_numeric($value) ? (int) $value : (int) basename($value);
    }
}
