<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Subscriber;

use InvalidArgumentException;
use PpPhp\Core\Platform\Event\Registry\EventListenerRegistry;

final class SubscriberRegistrar
{
    private array $records = [];

    public function register(EventListenerRegistry $registry, EventSubscriberInterface|string $subscriber): SubscriberRecord
    {
        $instance = is_string($subscriber) ? new $subscriber() : $subscriber;

        if (!$instance instanceof EventSubscriberInterface) {
            throw new InvalidArgumentException('Subscriber must implement EventSubscriberInterface.');
        }

        $class = $instance::class;
        $events = $class::subscribedEvents();

        foreach ($events as $eventName => $handler) {
            $method = null;
            $priority = 0;

            if (is_string($handler)) {
                $method = $handler;
            } elseif (is_array($handler)) {
                $method = (string) ($handler[0] ?? '');
                $priority = (int) ($handler[1] ?? 0);
            }

            if ($method === null || $method === '' || !method_exists($instance, $method)) {
                continue;
            }

            $registry->register((string) $eventName, [$instance, $method], $priority, ['subscriber'], [
                'subscriber' => $class,
                'method' => $method,
            ]);
        }

        $record = new SubscriberRecord($class, $events);
        $this->records[$class] = $record;

        return $record;
    }

    public function records(): array
    {
        return array_values($this->records);
    }
}
