<?php

namespace Licenzo\Framework\Foundation\Bootstrap;

use Licenzo\Framework\Config\Repository;
use Licenzo\Framework\Foundation\Application;
use Licenzo\Framework\Foundation\Dispatcher;
use Licenzo\Framework\Support\Arr;

class Bootstrapper
{
    protected $config = [];
    protected $app;

    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    public function bootstrap($config = [])
    {
        $this->config = $config;

        $this->app->instance('config',new Repository($this->loadConfiguration()));

        $this->app->singleton(Dispatcher::class, function ($app) {
            return new Dispatcher($app);
        });

        $this->app->alias(Dispatcher::class, 'dispatcher');

        $this->registerServiceProviders();
    }

    private function loadConfiguration()
    {
        $items = [];

        // Load configuration files if they exist
        $configPath = $this->app->basePath('config');

        if (is_dir($configPath)) {
            $items = $this->loadConfigurationFiles($configPath);
        }

        return $items;
    }

    protected function loadConfigurationFiles($configPath): array
    {
        $config = [];

        foreach (glob($configPath . '/*.php') ?: [] as $file) {

            try {
                $data = require $file;

                if (is_array($data)) {
                    $config[basename($file, '.php')] = $data;
                }

            } catch (\Throwable $e) {
                throw new \RuntimeException("Error loading configuration file: {$file}", 0, $e);
            }
        }

        return $config;
    }

    private function registerServiceProviders()
    {
        $providers = Arr::get($this->config, 'providers', []);

        foreach ($providers as $provider) {
            $this->app->register($provider);
        }
    }
}
