<?php

declare(strict_types=1);

namespace App\Framework\LiveComponents;

use App\Framework\DI\Attributes\Initializer;
use App\Framework\DI\Container;
use App\Framework\Discovery\Results\DiscoveryRegistry;
use App\Framework\LiveComponents\Attributes\DataProvider;

/**
 * DataProviderRegistrationInitializer
 *
 * Automatically registers all discovered DataProvider implementations
 * in the DI container as singletons.
 *
 * This allows the DataProviderResolver to instantiate providers via the container.
 */
final readonly class DataProviderRegistrationInitializer
{
    #[Initializer]
    public function __invoke(Container $container, DiscoveryRegistry $discoveryRegistry): void
    {
        // Get all classes with #[DataProvider] attribute
        $dataProviders = $discoveryRegistry->attributes->get(DataProvider::class);

        foreach ($dataProviders as $discovered) {
            // Get class name as string from ClassName value object
            $providerClass = $discovered->className->getFullyQualified();

            // Register provider as singleton in container
            // Use container to resolve dependencies automatically
            $container->singleton($providerClass, function (Container $container) use ($providerClass) {
                return $container->make($providerClass);
            });
        }
    }
}
