<?php

namespace Licenzo\Framework\Foundation;

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

/**
 * Base App Facade
 * @mixin Application
 * @method static \Licenzo\Framework\Http\Request request()
 * @method static \Licenzo\Framework\Http\Response\Response response()
 */
abstract class App
{
    /**
     * The application instance
     *
     * @var Application|null
     */
    protected static $instance = null;

    /**
     * Set the application instance
     *
     * @param Application $app
     * @return void
     */
    public static function setInstance(Application $app)
    {
        static::$instance = $app;
    }

    /**
     * Get the application instance
     *
     * @return Application
     * @throws \RuntimeException
     */
    public static function getInstance()
    {
        if (static::$instance === null) {
            throw new \RuntimeException('Application instance not set. Call App::setInstance() first.');
        }

        return static::$instance;
    }

    /**
     * Clear the application instance
     *
     * @return void
     */
    public static function clearInstance()
    {
        static::$instance = null;
    }

    /**
     * Handle dynamic static calls
     *
     * @param string $method
     * @param array $parameters
     * @return mixed
     */
    public static function __callStatic($method, $parameters)
    {
        $instance = static::getInstance();

        if (method_exists($instance, $method)) {
            return $instance->$method(...$parameters);
        }

        throw new \BadMethodCallException("Method [{$method}] does not exist on Application instance.");
    }

    public function __call($name, $arguments)
    {
        if(method_exists(static::$instance, $name)) {
            return $this->$name(...$arguments);
        }

        throw new \BadMethodCallException("Method [{$name}] does not exist on Application instance.");
    }
}
