<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Compiler\Stages;

use PpPhp\Core\Platform\Event\Compiler\EventArtifactWriter;
use PpPhp\Core\Platform\Event\Compiler\EventCompilerContext;
use PpPhp\Core\Platform\Event\Compiler\EventCompilerPaths;
use PpPhp\Core\Platform\Event\Compiler\EventCompilerStageInterface;
use PpPhp\Core\Platform\Event\Lifecycle\LifecycleEventManifest;

final class DispatchTableCompileStage implements EventCompilerStageInterface
{
    public function __construct(private readonly EventArtifactWriter $writer = new EventArtifactWriter()) {}

    public function name(): string { return 'dispatch-table'; }

    public function compile(EventCompilerContext $context): void
    {
        $dispatchTable = [];
        foreach (LifecycleEventManifest::registry()->all() as $event) {
            $dispatchTable[$event['name']] = [
                'event' => $event['name'],
                'class' => $event['class'],
                'category' => $event['category'],
                'listeners' => [],
            ];
        }
        foreach (($context->artifact('listenerMetadata')['registry']['records'] ?? []) as $record) {
            $eventName = $record['eventName'] ?? '';
            if ($eventName !== '') {
                $dispatchTable[$eventName] ??= ['event' => $eventName, 'class' => '', 'category' => 'custom', 'listeners' => []];
                $dispatchTable[$eventName]['listeners'][] = $record['id'];
            }
        }
        $data = ['generatedAt' => date('c'), 'count' => count($dispatchTable), 'dispatchTable' => $dispatchTable];
        $this->writer->writePhpArray(EventCompilerPaths::cacheFile($context->basePath(), 'compiled-dispatch-table.php'), $data);
        $context->setArtifact('dispatchTable', $data);
    }
}
