<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Resource;

use Builder\Core\Foundation\Contracts\Translatable;
use Builder\Core\Foundation\Definition\Section;
use Builder\Core\Foundation\Registry;
use Builder\Core\Http\Controllers\Concerns\HasResourceResolving;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

final class ResourceQuickMetaController
{
    use HasResourceResolving;

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

    public function __invoke(Request $request, string $resource): JsonResponse
    {
        $definition = $this->resolveOrFail($resource);
        $this->authorizeResource($request, $definition, 'create');

        $model = $definition->getModel();
        $modelInstance = new $model;
        $isTranslatable = $modelInstance instanceof Translatable;
        $locale = $isTranslatable ? $this->resolveContentLocale($request) : null;

        return response()->json([
            'sections' => array_map(fn (Section $s): array => $s->toArray(), $definition->getSections()),
            'singularLabel' => $definition->getSingularLabel(),
            'currentLocale' => $locale,
            'availableLocales' => $isTranslatable ? $this->resolveAvailableLanguages() : [],
        ]);
    }
}
