<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\hooks;

use apexl\Io\interfaces\AbstractHook;
use apexl\Io\modules\system\collections\MiddlewareCollectionCollection;
use apexl\Io\modules\system\services\MiddlewareCollector;
use apexl\Io\modules\user\Middleware\PermissionMiddleware;
use apexl\Io\modules\user\Middleware\SessionMiddleware;
use apexl\Io\modules\user\Middleware\TwoFactorMiddleware;

final readonly class AddMiddleware implements AbstractHook
{
    public function hooks(): array
    {
        return [MiddlewareCollector::HOOK__COLLECT];
    }

    public function __invoke(MiddlewareCollectionCollection $weightedMiddleware): MiddlewareCollectionCollection
    {
        // Order matters: these three share the MIDDLE weight group and are added
        // consecutively, so their relative execution order is preserved as
        // Session -> TwoFactor -> Permission. TwoFactorMiddleware needs the
        // `authenticated` attribute + loaded session that SessionMiddleware sets,
        // and must gate BEFORE PermissionMiddleware grants route access. When
        // 2FA mode is off, TwoFactorMiddleware short-circuits on its first line.
        $weightedMiddleware->add(SessionMiddleware::class);
        $weightedMiddleware->add(TwoFactorMiddleware::class);
        $weightedMiddleware->add(PermissionMiddleware::class);

        return $weightedMiddleware;
    }
}
