<?php

declare(strict_types=1);

namespace Apexl\Io\System\Services;

use Apexl\Io\HookManager;
use Apexl\Io\System\Collections\MiddlewareCollection;
use Apexl\Io\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);
    }
}