<?php

namespace App\Core;

/**
 * Application — Main Application Runner
 *
 * Coordinates the application lifecycle:
 *
 *   1. Bootstrap (INIT-003) — environment, config, helpers, error reporting
 *   2. Session::start()     — INIT-010
 *   3. Router::dispatch()   — INIT-007
 *
 * INIT-003 scope: Bootstrap + handleRequest() stub.
 * Router dispatch is added to handleRequest() in INIT-007.
 * Session start is added in INIT-010.
 *
 * @package Inveetaire
 * @ref     DBP v1.0 Ch.5, SAD v1.1 Ch.4, INIT-003
 */
class Application
{
    /**
     * The Bootstrap instance responsible for initialization.
     *
     * @var Bootstrap
     */
    private Bootstrap $bootstrap;

    /**
     * @param Bootstrap|null $bootstrap Optional bootstrap override (for testing).
     */
    public function __construct(?Bootstrap $bootstrap = null)
    {
        $this->bootstrap = $bootstrap ?? new Bootstrap();
    }

    /**
     * Boot the application and handle the incoming HTTP request.
     *
     * Execution order:
     *   1. Bootstrap::init()    — environment, helpers, error reporting
     *   2. Session::start()     — INIT-010 adds this step
     *   3. handleRequest()      — INIT-007 replaces stub with Router::dispatch()
     *
     * @return void
     */
    public function run(): void
    {
        // Step 1 — Initialize the application kernel.
        $this->bootstrap->init();

        // Step 2 — Session initialization.
        // Added in INIT-010: Session::start()
        // Deferred: see Session.php (INIT-010)

        // Step 3 — Dispatch the HTTP request.
        $this->handleRequest();
    }

    /**
     * Dispatch the incoming HTTP request via the Router.
     *
     * Execution:
     *   1. Create the Router instance.
     *   2. Load all route files from routes/ (5 portals).
     *   3. Build a Request from PHP superglobals (base-path stripped).
     *   4. Router::dispatch() matches the request and invokes the action.
     *      If no route matches → ErrorHandler::renderNotFound() → 404.
     *
     * INIT-009 (MiddlewarePipeline) wraps the action invocation.
     * Session::start() is added here in INIT-010.
     *
     * @return void
     */
    private function handleRequest(): void
    {
        $router = new Router();
        $router->loadRoutes(ROOT_PATH . '/routes');
        $router->dispatch(Request::fromGlobals());
    }

}
