<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Resource;

use Builder\Core\Foundation\Contracts\Translatable;
use Builder\Core\Foundation\Registry;
use Builder\Core\Http\Controllers\Concerns\HasResourceResolving;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

final class ResourceCreateController
{
    use HasResourceResolving;

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

    public function __invoke(Request $request, string $resource): Response
    {
        $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 Inertia::render('Resource/Form', [
            'resource' => $definition->toArray(),
            'record' => null,
            'currentLocale' => $locale,
            'availableLocales' => $isTranslatable ? $this->resolveAvailableLanguages() : [],
        ]);
    }
}
