<?php

declare(strict_types=1);

namespace apexl\Io\modules\system\services;

use apexl\Io\exceptions\ValidationException;
use apexl\Io\factories\IoRequestFactory;
use apexl\Io\Request\IoRequest;
use DI\DependencyException;
use DI\NotFoundException;
use Invoker\ParameterResolver\ParameterResolver;
use Psr\Http\Message\ServerRequestInterface;
use ReflectionFunctionAbstract;
use ReflectionParameter;

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

    /**
     * @throws DependencyException
     * @throws ValidationException
     * @throws NotFoundException
     */
    public function getParameters(ReflectionFunctionAbstract $reflection, array $providedParameters, array $resolvedParameters): array
    {

        $parameters = $reflection->getParameters();
        $originalRequest = $providedParameters['request'] ?? null;

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

        $requestedRequestIx = array_find_key(
            $parameters,
            fn(ReflectionParameter $parameter) => $parameter->getName() === 'request'
        );

        if ($requestedRequestIx === false) {
            return $resolvedParameters;
        }

        $requestedRequestClass = $parameters[$requestedRequestIx]->getType()->getName();

        if ($requestedRequestClass && is_subclass_of($requestedRequestClass, IoRequest::class)) {
            $resolvedParameters[$requestedRequestIx] = $this->ioRequestFactory->fromRequest(
                $requestedRequestClass,
                $originalRequest
            );
        }

        return $resolvedParameters;
    }


    private function getRequest(array $resolvedParameters): ?ServerRequestInterface
    {
        return array_find($resolvedParameters, fn($parameter) => $parameter instanceof ServerRequestInterface);
    }
}