<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Lifecycle;

final class LifecycleEventCompiler
{
    public const CACHE_FILE = 'storage/cache/events/compiled-lifecycle-events.php';

    public function compile(string $basePath): array
    {
        $registry = LifecycleEventManifest::registry();
        $data = [
            'generatedAt' => date('c'),
            'count' => $registry->count(),
            'categories' => $registry->categories(),
            'events' => $registry->all(),
        ];

        $file = rtrim($basePath, DIRECTORY_SEPARATOR) . '/' . self::CACHE_FILE;
        if (!is_dir(dirname($file))) {
            mkdir(dirname($file), 0775, true);
        }

        file_put_contents($file, "<?php\nreturn " . var_export($data, true) . ";\n");

        return $data;
    }
}
