<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Resource;

use Builder\Core\Foundation\Contracts\BuilderAccessible;
use Builder\Core\Foundation\Enums\ToastType;
use Builder\Core\Foundation\Middleware\BuilderAuth;
use Builder\Core\Foundation\Registry;
use Builder\Core\Foundation\Resources\ResourcePersistenceService;
use Builder\Core\Foundation\Support\Toast;
use Builder\Core\Http\Controllers\Concerns\HasResourceResolving;
use Builder\Core\Http\Requests\Resource\StoreResourceRequest;
use Illuminate\Http\RedirectResponse;

final class ResourceStoreController
{
    use HasResourceResolving;

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

    public function __invoke(StoreResourceRequest $request, string $resource): RedirectResponse
    {
        $definition = $this->resolveOrFail($resource);

        /** @var BuilderAccessible $user */
        $user = $request->user(BuilderAuth::guard());

        $data = $this->persistenceService->stripRestrictedFields($request->validated(), $definition, $user);
        $locale = $request->input('_locale');

        $this->persistenceService->store($definition, $data, $locale, $user);

        return redirect()->route('builder.resource.index', array_filter(['resource' => $resource, 'locale' => $locale]))
            ->with(Toast::flash(ToastType::Success, __('builder::builder.resources.created')));
    }
}
