<?php

declare(strict_types=1);

namespace apexl\Io\modules\system\services;

use apexl\Io\includes\HookManager;
use apexl\Io\modules\system\collections\MiddlewareCollection;
use apexl\Io\modules\system\collections\MiddlewareCollectionCollection;

final readonly class MiddlewareCollector
{
    public final const int WEIGHT__FIRST = 100;
    public final const int WEIGHT__MIDDLE = 300;
    public final const int WEIGHT__LAST = 500;
    public final const string HOOK__COLLECT = 'middleware.collect';

    public function __construct(
        private HookManager $hookManager,
    ) {}

    public function collect(): MiddlewareCollectionCollection
    {
        $middleware = new MiddlewareCollectionCollection();
        $this->hookManager->processHook(self::HOOK__COLLECT, $middleware);

        return $middleware
            ->map(fn(MiddlewareCollection $middlewareCollection) => $middlewareCollection->krsort())
            ->krsort(SORT_NATURAL);
    }
}