<?php

declare(strict_types=1);

namespace apexl\Io\modules\system\services;

use apexl\Io\exceptions\ValidationException;
use apexl\Io\factories\RequestHelperFactory;
use apexl\Io\requestHelper\requestHelper;
use DI\DependencyException;
use DI\NotFoundException;
use Invoker\ParameterResolver\ParameterResolver;
use Psr\Http\Message\ServerRequestInterface;
use ReflectionFunctionAbstract;

final readonly class RequestHelperResolver implements ParameterResolver
{
    public function __construct(private RequestHelperFactory $requestHelperFactory) {}

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

        // Skip parameters already resolved
        if (!empty($resolvedParameters)) {
            $parameters = array_diff_key($parameters, $resolvedParameters);
        }

        $request = $this->getRequest($resolvedParameters);

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

        foreach ($parameters as $ix => $parameter) {
            if (!$parameter->hasType()) {
                continue;
            }
            $typeClass = $parameter->getType()->getName();

            if (is_subclass_of($parameter->getType()->getName(), RequestHelper::class)) {
                $resolvedParameters[$ix] = $this->requestHelperFactory->make($typeClass, $request);
            }
        }

        return $resolvedParameters;
    }


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