<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);

namespace BookiFlex\Core\Contract\DeferrerEvent;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;

defined( 'ABSPATH' ) || exit;

/**
 * This class is responsible for releasing deferred events from objects and dispatching them.
 */
class EventsReleaser
{
    private DomainEventCollector $collector;

    public function __construct(
        private readonly EventDispatcherInterface $eventDispatcher,
    ) {
        $this->collector = new DomainEventCollector();
    }

    public function releaseEvents(array $objects): void
    {
        if (empty($objects)) {
            return;
        }

        foreach ($objects as $object) {
            if ($object instanceof DeferredEventSupportInterface) {
                $events = $object->releaseDeferredEvents();
                foreach ($events as $event) {
                    $this->collector->collect($event);
                }
            }
        }

        $this->collector->dispatch($this->eventDispatcher);
    }
}
