<?php

/*
 * ================================================================
 *  CORE TEMPLATE FILE - DO NOT MODIFY
 * ================================================================
 * This file is part of the shared wefulfil-core-template Template.
 * 
 * Developers must NOT edit or alter this file directly.
 * Any proposed changes or improvements should be discussed
 * with your Team Lead or Line Manager for review and approval.
 * 
 * Local changes will be overwritten when the template is updated
 * Contact Team Lead or Line Manager for any requested modifications
 *
 * Unauthorized modifications may cause conflict or inconsistencies
 * across services that rely on this core template.
 * ================================================================
 */

class Middleware
{
    private static array $middlewares = [];
    private static array $excluded    = [];

    // ── Register middleware stack ─────────────────────────────
    public static function stack(array $middlewares): static
    {
        self::$middlewares = $middlewares;
        return new static();
    }

    // ── Exclude specific middleware by class name ─────────────
    public static function except(array $excluded): static
    {
        self::$excluded = $excluded;
        return new static();
    }

    // ── Run the stack ─────────────────────────────────────────
    public static function run(): void
    {
        foreach (self::$middlewares as $middleware) {

            if (in_array($middleware, self::$excluded, true)) {
                continue;
            }

            if (!class_exists($middleware)) {
                Response::simple(true, "Middleware '$middleware' not found", 500);
            }

            if (!method_exists($middleware, 'handle')) {
                Response::simple(true, "Middleware '$middleware' missing handle() method", 500);
            }

            $middleware::handle();
        }
    }

    // ── Preset stacks ─────────────────────────────────────────
    public static function public(): void
    {
        self::stack([
            'CorsMiddleware',
            'LoggingMiddleware',
            'RateLimitMiddleware',
        ])->run();
    }

    public static function private(): void
    {
        self::stack([
            'CorsMiddleware',
            'LoggingMiddleware',
            'AuthMiddleware',
            'RateLimitMiddleware',
            'TenantMiddleware',
        ])->run();
    }

    public static function admin(): void
    {
        self::stack([
            'CorsMiddleware',
            'LoggingMiddleware',
            'AuthMiddleware',
            'RateLimitMiddleware',
            'AdminMiddleware',
        ])->run();
    }
}