<?php
/**
 * Application Builder
 *
 * @package Licenzo\Framework\Foundation
 */

namespace Licenzo\Framework\Foundation;

use Licenzo\Framework\Foundation\Bootstrap\Bootstrapper;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Fluent application configuration builder
 */
class ApplicationBuilder
{

    /**
     * Additional configuration
     *
     * @var array
     */
    protected $config = [];

    protected $afterCallback;

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

    public function bootstrap($config)
    {
        $acceptableConfig = ['debug', 'root_path', 'providers', 'exception_handlers'];

        foreach ($config as $key => $value) {
            if (!in_array($key, $acceptableConfig)) {
                throw new \InvalidArgumentException("Invalid configuration key: {$key}");
            }
        }

        $this->config = array_merge($this->config, $config);
    }

    /**
     * @throws \Throwable
     */
    public function create(): ?Application
    {
        return $this->build();
    }

    public function build(): Application
    {
        $app = new Application($this->config['root_path']);
        $app->make(Bootstrapper::class)->bootstrap($this->config);
        $app->call($this->afterCallback);
        $app->bootstrap();
        return $app;
    }

    public function after($callback)
    {
        $this->afterCallback = $callback;
        return $this;
    }
}
