<?php

namespace App\PageBuilder;

use Illuminate\Support\Facades\Log;

class ComponentRegistry
{
    /** @var array<string, string> key => Component::class */
    private array $components = [];

    public function register(string $key, string $componentClass): void
    {
        if (! is_subclass_of($componentClass, PageComponent::class)) {
            throw new \InvalidArgumentException("{$componentClass} must extend PageComponent");
        }
        $this->components[$key] = $componentClass;
    }

    public function resolve(string $key): ?PageComponent
    {
        $class = $this->components[$key] ?? null;
        if (! $class) return null;

        return app($class);
    }

    public function all(): array
    {
        return collect($this->components)
            ->map(fn ($class) => app($class))
            ->all();
    }

    public function byCategory(): array
    {
        return collect($this->all())
            ->groupBy(fn (PageComponent $c) => $c->category())
            ->map(fn ($items) => $items->values()->all())
            ->all();
    }

    public function jsBlockDefinitions(): array
    {
        return collect($this->all())
            ->mapWithKeys(fn (PageComponent $c) => [$c->key() => $c->jsBlockDefinition()])
            ->all();
    }
}
