<?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\Resources\RecordAction;
use Builder\Core\Foundation\Support\Toast;
use Builder\Core\Http\Controllers\Concerns\HasResourceResolving;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

final class ResourceRecordActionController
{
    use HasResourceResolving;

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

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

        $recordAction = collect($definition->getRecordActions())->first(
            fn (RecordAction $a): bool => $a->key === $action,
        );

        abort_if($recordAction === null, 404);

        $record = $definition->getModel()::findOrFail($id);
        $recordAction->execute($record, $request);

        return redirect()->back()
            ->with(Toast::flash(ToastType::Success, __('builder::builder.invite.invite_sent')));
    }
}
