<?php

/** @noinspection ALL */

namespace DefStudio\GameEngine\Actions\Livewire\Sortable;

use DefStudio\Actions\Action;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Gate;
use Illuminate\Database\Eloquent\Model;

/**
 * @method static void run(Collection $models, array $new_order)
 */
class UpdateOrder extends Action
{
    /**
     * @param  Collection<int, Model>  $models
     */
    public function handle(Collection $models, array $new_order): void
    {
        collect($new_order)
            ->each(function(array $item) use ($models): void {
                /** @var Model $model */
                $model = $models->firstOrFail('id', $item['value']);

                Gate::authorize('update', $model);

                $model->setAttribute('order', $item['order']);
                $model->save();
            });
    }
}
