<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Consumer\Hydration;

use PpPhp\Core\Platform\Event\Consumer\QueueConsumerManager;

final class QueueConsumerCrossProcessHydrator
{
    private QueueConsumerStateMerger $merger;
    private QueueConsumerSnapshotReconciler $reconciler;
    private QueueConsumerStateValidator $validator;

    public function __construct(private readonly QueueConsumerManager $manager)
    {
        $this->merger = new QueueConsumerStateMerger();
        $this->reconciler = new QueueConsumerSnapshotReconciler();
        $this->validator = new QueueConsumerStateValidator();
    }

    public function hydrate(): array
    {
        $liveStats = $this->manager->consumer()->statistics()->toArray();
        $liveSnapshot = $this->manager->consumer()->snapshot()->toArray();
        $liveBatchStats = method_exists($this->manager->consumer(), 'batchEngine')
            ? $this->manager->consumer()->batchEngine()->statistics()->toArray()
            : [];

        $persisted = $this->manager->load();

        $statistics = $this->merger->mergeStatistics($liveStats, $persisted->statistics());
        $snapshot = $this->reconciler->reconcile(
            $this->merger->mergeSnapshot($liveSnapshot, $persisted->snapshot())
        );
        $batchStatistics = $this->merger->mergeBatchStatistics($liveBatchStats, $persisted->batchStatistics());

        $state = [
            'statistics' => $statistics,
            'snapshot' => $snapshot,
            'batchStatistics' => $batchStatistics,
            'persisted' => $this->manager->store()->exists(),
            'stateFile' => $this->manager->store()->stateFile(),
        ];

        $state['validation'] = $this->validator->validate([
            'statistics' => $statistics,
            'snapshot' => $snapshot,
            'batchStatistics' => $batchStatistics,
        ]);

        return $state;
    }
}
