<?php

declare(strict_types=1);

namespace apexl\Io\modules\system\services;

use apexl\Io\factories\IoRequestFactory;
use apexl\Io\Request\IoRequest;
use DI\DependencyException;
use DI\NotFoundException;
use Psr\Http\Message\ServerRequestInterface;
use ReflectionException;
use ReflectionFunctionAbstract;
use ReflectionParameter;

final readonly class RequestResolver
{
    public function __construct(
        private IoRequestFactory $ioRequestFactory,
    ) {}

    /**
     * @throws DependencyException
     * @throws NotFoundException
     * @throws ReflectionException
     */
    public function resolve(ReflectionFunctionAbstract $reflection, ServerRequestInterface $originalRequest): ServerRequestInterface
    {
        $parameters = $reflection->getParameters();

        $requestedRequest = array_find(
            $parameters,
            fn(ReflectionParameter $parameter) => $parameter->getName() === 'request'
        );

        if (!$requestedRequest) {
            return $originalRequest;
        }

        $requestedRequestClass = $requestedRequest->getType()->getName();

        if (is_subclass_of($requestedRequestClass, IoRequest::class)) {
            return $this->ioRequestFactory->fromRequest(
                $requestedRequestClass,
                $originalRequest
            );
        }

        return $originalRequest;
    }
}