<?php

declare(strict_types=1);

namespace App\Support\References;

use App\Support\References\Contracts\ReferenceResolver;

final class ReferenceResolverRegistry
{
    /**
     * @param  iterable<int, ReferenceResolver>  $resolvers
     */
    public function __construct(
        iterable $resolvers,
        private readonly ReferenceResolver $fallbackResolver,
    ) {
        foreach ($resolvers as $resolver) {
            $this->resolvers[$resolver->referenceClass()->value] = $resolver;
        }
    }

    /**
     * @var array<string, ReferenceResolver>
     */
    private array $resolvers = [];

    public function resolverFor(ReferenceClass $referenceClass): ReferenceResolver
    {
        return $this->resolvers[$referenceClass->value] ?? $this->fallbackResolver;
    }

    public function resolve(ReferenceDescriptor $descriptor): ResolvedReference
    {
        return $this->resolverFor($descriptor->referenceClass)->resolve($descriptor);
    }
}
