<?php

namespace Maestro\Core\DataTables;

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

/**
 * Registry mapping resourceKey => DataTableResource class.
 * Resolves resource instances for the generic DataTable controller.
 */
class DataTableRegistry
{
    /**
     * @var array<string, class-string<DataTableResource>>
     */
    private array $map = [];

    /**
     * Register a resource class under the given key (or the resource's key()).
     *
     * @param  class-string<DataTableResource>  $resourceClass
     */
    public function register(string $resourceClass, ?string $key = null): void
    {
        $instance = app($resourceClass);
        if (! $instance instanceof DataTableResource) {
            throw new \InvalidArgumentException(sprintf(
                'Class %s must implement %s',
                $resourceClass,
                DataTableResource::class
            ));
        }
        $key = $key ?? $instance->key();
        $this->map[$key] = $resourceClass;
    }

    /**
     * Resolve a resource by key. Throws 404 when unknown.
     *
     * @return DataTableResource
     */
    public function resolve(string $resourceKey): DataTableResource
    {
        if (! isset($this->map[$resourceKey])) {
            throw new NotFoundHttpException(sprintf('DataTable resource "%s" is not registered.', $resourceKey));
        }

        $resource = app($this->map[$resourceKey]);
        if (! $resource instanceof DataTableResource) {
            throw new \RuntimeException(sprintf('Resolved class for "%s" does not implement DataTableResource.', $resourceKey));
        }

        return $resource;
    }

    /**
     * Return all registered keys (for debugging or discovery).
     *
     * @return array<int, string>
     */
    public function keys(): array
    {
        return array_keys($this->map);
    }
}
