<?php

declare(strict_types=1);

namespace App\Framework\Router;

use App\Framework\DI\DefaultContainer;
use App\Framework\Http\Request;
use App\Framework\Http\RequestBody;
use App\Framework\Http\Session\Session;
use App\Framework\Validation\Exceptions\ValidationException;
use App\Framework\Validation\Validator;
use Exception;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionProperty;

final readonly class ControllerRequestFactory
{
    public function __construct(
        private DefaultContainer       $container,
        private PropertyValueConverter $propertyValueConverter
    ) {}

    /**
     * Erstellt und validiert eine ControllerRequest-Instanz
     */
    public function createAndValidate(ReflectionClass $requestClass, RequestBody $data): object
    {
        // Instanz erstellen
        $instance = $requestClass->newInstance();

        // Eigenschaften befüllen und validieren
        foreach ($requestClass->getProperties() as $property) {
            $propertyName = $property->getName();

            // Wert aus den Daten abrufen
            $value = $data->get($propertyName, null);

            try {
                $this->propertyValueConverter->setPropertyValue($property, $instance, $value);
            } catch (\Throwable $e) {
                #throw new ValidationException(
                #    ['Ungültiger Wert für den Typ: ' . $e->getMessage()],
                #    $propertyName
                #);
            }
        }

        $validator = $this->container->get(Validator::class);

        $validationResult = $validator->validate($instance);

        if ($validationResult->hasErrors()) {

            throw new ValidationException($validationResult, 'test');
        }

        return $instance;
    }
}
