<?php

declare(strict_types=1);

namespace App\Framework\HttpClient;

use App\Framework\Core\ValueObjects\Duration;
use App\Framework\Http\Method;

/**
 * Fluent Builder für AsyncHttpClient
 *
 * Vereinfacht die Erstellung von HTTP Requests mit async Funktionalität
 */
final class AsyncHttpClientBuilder
{
    private array $requests = [];

    private ?int $maxConcurrency = null;

    private ?Duration $timeout = null;

    private ?Duration $retryDelay = null;

    private int $maxRetries = 0;

    public function __construct(
        private readonly AsyncHttpClientDecorator $client
    ) {
    }

    /**
     * Füge GET Request hinzu
     */
    public function get(string $key, string $url, array $headers = []): self
    {
        return $this->addRequest($key, Method::GET, $url, '', $headers);
    }

    /**
     * Füge POST Request hinzu
     */
    public function post(string $key, string $url, mixed $body = '', array $headers = []): self
    {
        return $this->addRequest($key, Method::POST, $url, $body, $headers);
    }

    /**
     * Füge PUT Request hinzu
     */
    public function put(string $key, string $url, mixed $body = '', array $headers = []): self
    {
        return $this->addRequest($key, Method::PUT, $url, $body, $headers);
    }

    /**
     * Füge DELETE Request hinzu
     */
    public function delete(string $key, string $url, array $headers = []): self
    {
        return $this->addRequest($key, Method::DELETE, $url, '', $headers);
    }

    /**
     * Füge JSON POST Request hinzu
     */
    public function postJson(string $key, string $url, array $data, array $headers = []): self
    {
        $request = ClientRequest::json(Method::POST, $url, $data);
        $this->requests[$key] = $request;

        return $this;
    }

    /**
     * Füge JSON PUT Request hinzu
     */
    public function putJson(string $key, string $url, array $data, array $headers = []): self
    {
        $request = ClientRequest::json(Method::PUT, $url, $data);
        $this->requests[$key] = $request;

        return $this;
    }

    /**
     * Setze maximale Nebenläufigkeit
     */
    public function withConcurrency(int $maxConcurrency): self
    {
        $this->maxConcurrency = $maxConcurrency;

        return $this;
    }

    /**
     * Setze Timeout für alle Requests
     */
    public function withTimeout(Duration $timeout): self
    {
        $this->timeout = $timeout;

        return $this;
    }

    /**
     * Aktiviere Retry mit exponential backoff
     */
    public function withRetry(int $maxRetries, ?Duration $initialDelay = null): self
    {
        $this->maxRetries = $maxRetries;
        $this->retryDelay = $initialDelay ?? Duration::fromSeconds(1);

        return $this;
    }

    /**
     * Führe alle Requests parallel aus
     */
    public function execute(): array
    {
        if (empty($this->requests)) {
            return [];
        }

        // Apply timeout to individual requests if specified
        if ($this->timeout !== null) {
            $wrappedRequests = [];
            foreach ($this->requests as $key => $request) {
                $wrappedRequests[$key] = fn () => $this->client->sendWithTimeout($request, $this->timeout);
            }

            if ($this->maxConcurrency !== null) {
                return $this->client->sendBatch($wrappedRequests, $this->maxConcurrency);
            } else {
                $operations = [];
                foreach ($wrappedRequests as $key => $operation) {
                    $operations[$key] = $operation;
                }

                return array_map(fn ($op) => $op(), $operations);
            }
        }

        // Apply retry logic if specified
        if ($this->maxRetries > 0) {
            $wrappedRequests = [];
            foreach ($this->requests as $key => $request) {
                $wrappedRequests[$key] = fn () => $this->client->sendWithRetry(
                    $request,
                    $this->maxRetries,
                    $this->retryDelay
                );
            }

            if ($this->maxConcurrency !== null) {
                return $this->client->sendBatch($wrappedRequests, $this->maxConcurrency);
            } else {
                return array_map(fn ($op) => $op(), $wrappedRequests);
            }
        }

        // Standard parallel execution
        if ($this->maxConcurrency !== null) {
            return $this->client->sendBatch($this->requests, $this->maxConcurrency);
        } else {
            return $this->client->sendMultiple($this->requests);
        }
    }

    /**
     * Führe als Aggregation aus (mit Fehlerbehandlung)
     */
    public function executeAsAggregation(): array
    {
        return $this->client->aggregate($this->requests);
    }

    /**
     * Führe als Health Check aus
     */
    public function executeAsHealthCheck(): array
    {
        $urls = [];
        foreach ($this->requests as $key => $request) {
            $urls[$key] = $request->url;
        }

        return $this->client->healthCheck($urls, $this->timeout);
    }

    /**
     * Führe Race-Pattern aus (erste erfolgreiche Response)
     */
    public function executeAsRace(): ClientResponse
    {
        return $this->client->race(array_values($this->requests));
    }

    /**
     * Sammle Responses mit Custom Processor
     */
    public function collect(callable $processor): array
    {
        return $this->client->collect($this->requests, $processor);
    }

    /**
     * Reset Builder für Wiederverwendung
     */
    public function reset(): self
    {
        $this->requests = [];
        $this->maxConcurrency = null;
        $this->timeout = null;
        $this->retryDelay = null;
        $this->maxRetries = 0;

        return $this;
    }

    /**
     * Erstelle neuen Builder
     */
    public static function create(AsyncHttpClientDecorator $client): self
    {
        return new self($client);
    }

    private function addRequest(string $key, Method $method, string $url, mixed $body, array $headers): self
    {
        $headerObj = new \App\Framework\Http\Headers();
        foreach ($headers as $name => $value) {
            $headerObj = $headerObj->with($name, $value);
        }

        $this->requests[$key] = new ClientRequest($method, $url, $headerObj, $body);

        return $this;
    }
}

// Extension method for easier access
if (! function_exists('asyncHttp')) {
    function asyncHttp(AsyncHttpClientDecorator $client): AsyncHttpClientBuilder
    {
        return AsyncHttpClientBuilder::create($client);
    }
}
