<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Resource;

use Builder\Core\Exceptions\DeletionDeniedException;
use Builder\Core\Foundation\Contracts\BuilderAccessible;
use Builder\Core\Foundation\Enums\ToastType;
use Builder\Core\Foundation\Events\ResourceRecordDeleted;
use Builder\Core\Foundation\Middleware\BuilderAuth;
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;
use Illuminate\Support\Facades\Event;

final class ResourceDestroyController
{
    use HasResourceResolving;

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

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

        $record = $model::findOrFail($id);

        try {
            $definition->canDelete($record);
        } catch (DeletionDeniedException $e) {
            return redirect()->back()
                ->with(Toast::flash(ToastType::Error, $e->getMessage() ?: (string) __('builder::builder.resources.cannot_delete')));
        }

        $record->delete();

        /** @var BuilderAccessible $user */
        $user = $request->user(BuilderAuth::guard());
        Event::dispatch(new ResourceRecordDeleted($definition, $record, $user));

        $locale = $request->query('locale') ?: null;

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