<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Streaming\Publisher;

use PpPhp\Core\Platform\Event\Streaming\MessageBus;

final class PublisherManager
{
    private static ?self $instance = null;

    private PublisherCollection $publishers;
    /** @var PublishRequest[] */
    private array $requests = [];
    /** @var PublishResult[] */
    private array $results = [];
    private PublisherStore $store;

    private function __construct(private readonly string $basePath)
    {
        $this->publishers = new PublisherCollection();
        $this->store = new PublisherStore($basePath);
        $this->hydrate();
    }

    public static function instance(?string $basePath = null): self
    {
        if (self::$instance === null) {
            $basePath ??= self::detectBasePath();
            self::$instance = new self($basePath);
        }

        return self::$instance;
    }

    public static function resetInstance(?string $basePath = null): self
    {
        $basePath ??= self::detectBasePath();
        self::$instance = new self($basePath);

        return self::$instance;
    }

    public function publish(PublishRequest $request): PublishResult
    {
        $pipeline = new PublisherPipeline(MessageBus::instance($this->basePath));
        $result = $pipeline->publish($request);

        $this->requests[] = $request;
        $this->results[] = $result;
        $this->publishers->record($request->publisherId(), $result);

        $this->save();

        return $result;
    }

    public function publishBatch(array $requests): array
    {
        $results = [];

        foreach ($requests as $request) {
            if ($request instanceof PublishRequest) {
                $results[] = $this->publish($request);
            }
        }

        return $results;
    }

    public function hydrate(): void
    {
        $snapshot = $this->store->load();

        if ($snapshot->publishers() !== []) {
            $this->publishers = PublisherCollection::fromArray($snapshot->publishers());
        }

        $this->requests = [];
        foreach ($snapshot->requests() as $request) {
            if (is_array($request)) {
                $this->requests[] = PublishRequest::fromArray($request);
            }
        }

        $this->results = [];
        foreach ($snapshot->results() as $result) {
            if (is_array($result)) {
                $this->results[] = PublishResult::fromArray($result);
            }
        }
    }

    public function snapshot(): PublisherSnapshot
    {
        $publishers = $this->publishers->toArray();
        $requests = array_map(static fn (PublishRequest $request): array => $request->toArray(), $this->requests);
        $results = array_map(static fn (PublishResult $result): array => $result->toArray(), $this->results);

        return new PublisherSnapshot(
            $publishers,
            $requests,
            $results,
            PublisherStatistics::from($publishers, $requests, $results),
            date('c')
        );
    }

    public function save(): PublisherSnapshot
    {
        return $this->store->save($this->snapshot());
    }

    public function clear(): void
    {
        $this->publishers = new PublisherCollection();
        $this->requests = [];
        $this->results = [];
        $this->store->reset();
    }

    public function store(): PublisherStore { return $this->store; }

    public function summary(): array
    {
        $snapshot = $this->snapshot();

        return [
            'publishers' => $snapshot->publishers(),
            'requests' => $snapshot->requests(),
            'results' => $snapshot->results(),
            'statistics' => $snapshot->statistics(),
            'persisted' => $this->store->exists(),
            'stateFile' => $this->store->stateFile(),
        ];
    }

    private static function detectBasePath(): string
    {
        $candidate = dirname(__DIR__, 5);
        $real = realpath($candidate);
        return $real !== false ? $real : $candidate;
    }
}
