<?php

declare(strict_types=1);

namespace App\Framework\EventSourcing;

use App\Framework\Core\ValueObjects\Timestamp;
use App\Framework\DateTime\Clock;

final readonly class AggregateRootRepository
{
    public function __construct(
        private EventStore $eventStore,
        private Clock $clock,
    ) {
    }

    public function load(AggregateId $aggregateId, object $state): AggregateRoot
    {
        $events = $this->eventStore->loadStream($aggregateId);

        return AggregateRoot::rehydrate(
            aggregateId: $aggregateId,
            state: $state,
            events: $events
        );
    }

    public function save(AggregateRoot $root): void
    {

        $events = $root->eventRecorder->pullRecordedEvents();

        $ae = new AggregateEnvelope(
            aggregateId: $root->id,
            event      : $events[0],
            version    : $root->eventRecorder->version,
            recordedAt : Timestamp::fromClock($this->clock),
            metadata   : new EventMetadata('actor')
        );

        $this->eventStore->append($ae);
    }
}
