<?php

namespace Openguru\OpenCartFramework;

use Openguru\OpenCartFramework\Container\Container;
use Openguru\OpenCartFramework\Container\ServiceProvider;
use Openguru\OpenCartFramework\Settings\DatabaseUserSettings;
use Openguru\OpenCartFramework\Settings\UserSettingsInterface;
use Openguru\OpenCartFramework\Support\SupportServiceProvider;
use RuntimeException;

class DependencyRegistration
{
    public static function register(Container $container, array $serviceProviders = []): void
    {
        $container->singleton(UserSettingsInterface::class, function (Container $container) {
            return $container->get(DatabaseUserSettings::class);
        });

        $container->get(SupportServiceProvider::class)->register();

        static::registerServiceProviders($container, $serviceProviders);
    }

    private static function registerServiceProviders(Container $container, array $serviceProviders): void
    {
        foreach ($serviceProviders as $serviceProvider) {
            $provider = $container->get($serviceProvider);
            if (! $provider instanceof ServiceProvider) {
                throw new RuntimeException('ServiceProvider must extend ServiceProvider');
            }

            $provider->register();
        }
    }
}
