<?php

namespace Licenzo\Framework\Http\Middleware;

use Licenzo\Framework\Foundation\Application;
use Licenzo\Framework\Http\Request;
use Licenzo\Framework\Http\Response;
use Closure;

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

/**
 * Abstract Middleware Base Class
 *
 * Provides a base implementation for HTTP middleware with shared utilities
 * and optional termination support.
 */
abstract class AbstractMiddleware
{
    /**
     * The application instance.
     */
    protected Application $app;

    /**
     * Create a new middleware instance.
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Handle an incoming request.
     *
     * This method must be implemented by all middleware subclasses.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    abstract public function handle(Request $request, Closure $next);

    /**
     * Perform any final work for the request lifecycle.
     *
     * This method is called after the response has been sent to the user.
     * Override this method in subclasses that need to perform cleanup tasks.
     *
     * @param Request $request
     * @param Response $response
     * @return void
     */
    public function terminate(Request $request, Response $response): void
    {
        // Default implementation does nothing
        // Subclasses can override this method to perform cleanup tasks
    }

    /**
     * Log an error message.
     *
     * @param string $message
     * @param \Throwable|null $exception
     * @return void
     */
    protected function logError(string $message, \Throwable $exception = null): void
    {
        if (!function_exists('error_log')) {
            return;
        }

        $logMessage = '[Licenzo Middleware] ' . $message;
        
        if ($exception) {
            $logMessage .= ' - ' . $exception->getMessage();
        }

        error_log($logMessage);
    }

    /**
     * Check if the application is in debug mode.
     *
     * @return bool
     */
    protected function isDebugMode(): bool
    {
        return defined('WP_DEBUG') && WP_DEBUG;
    }

    /**
     * Fire a WordPress action hook.
     *
     * @param string $hook
     * @param array $args
     * @return void
     */
    protected function fireHook(string $hook, array $args = []): void
    {
        if (function_exists('do_action')) {
            do_action($hook, ...$args);
        }
    }

    /**
     * Get the application instance.
     *
     * @return Application
     */
    protected function getApp(): Application
    {
        return $this->app;
    }
}
