<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers;

use Builder\Core\Foundation\Assets;
use Builder\Core\Foundation\Definition\JsModule;
use Builder\Core\Foundation\Registry;
use Illuminate\Http\JsonResponse;

final class ModuleManifestController
{
    public function __construct(private readonly Registry $registry) {}

    public function __invoke(): JsonResponse
    {
        $modules = collect($this->registry->all())
            ->filter(fn (JsModule $module): bool => $module->getPublicPath() !== null)
            ->map(fn (JsModule $module): array => [
                'key' => $module->getKey(),
                'label' => $module->getLabel(),
                'entry' => Assets::entryUrl($module->getKey(), $module->getEntry()),
            ])
            ->values()
            ->all();

        return response()->json(['modules' => $modules]);
    }
}
