<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\services\twoFactorAuth;

use apexl\Io\modules\user\exceptions\TwoFactorException;
use apexl\Io\modules\user\interfaces\TwoFactorMethodInterface;
use apexl\Io\modules\user\services\twoFactorAuth\methods\TotpMethod;

/**
 * Resolves a `TwoFactorMethodInterface` by its persisted `type` name. Replaces
 * V1's glob()-based directory scan with an explicit, injected list (Plan 007
 * §5.1) — faster, and it can't silently pick up stray files. A future WebAuthn
 * method is added here (and to services.php), nowhere else.
 */
final class TwoFactorMethodRegistry
{
    /** @var array<string, TwoFactorMethodInterface> */
    private array $methods = [];

    public function __construct(TotpMethod $totpMethod)
    {
        $this->register($totpMethod);
    }

    public function register(TwoFactorMethodInterface $method): void
    {
        $this->methods[$method->getMethodName()] = $method;
    }

    /**
     * @throws TwoFactorException when no method is registered under $name
     */
    public function get(string $name): TwoFactorMethodInterface
    {
        return $this->methods[$name]
            ?? throw new TwoFactorException(sprintf('Unknown two-factor method: %s', $name));
    }

    public function default(): TwoFactorMethodInterface
    {
        return $this->get(TotpMethod::NAME);
    }
}
