<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Resource;

use Builder\Core\Foundation\Enums\ToastType;
use Builder\Core\Foundation\Registry;
use Builder\Core\Foundation\Support\Toast;
use Builder\Core\Http\Controllers\Concerns\HasResourceResolving;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

final class ResourceDuplicateController
{
    use HasResourceResolving;

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

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

        abort_unless($definition->isDuplicatable(), 404);

        $this->authorizeResource($request, $definition, 'store');

        $original = $definition->getModel()::findOrFail($id);
        $resourceInstance = $definition->getResource();
        $clone = $resourceInstance->duplicate($original);
        $clone->save();
        $resourceInstance->postDuplicate($original, $clone);

        return redirect()->route('builder.resource.edit', ['resource' => $resource, 'id' => $clone->getKey()])
            ->with(Toast::flash(ToastType::Success, __('builder::builder.resources.duplicated', [
                'label' => $definition->getSingularLabel(),
            ])));
    }
}
