<?php

namespace DefStudio\GameEngine\Actions\Tasks;

use DefStudio\Actions\Action;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\Task;
use DefStudio\GameEngine\Events\Tasks\TaskSaved;
use DefStudio\GameEngine\Events\Tasks\TaskCreated;
use DefStudio\GameEngine\Events\Tasks\TaskUpdated;
use DefStudio\GameEngine\Decorators\Tasks\TaskDecorator;

/**
 * @method static Task run(Task|TaskDecorator $task)
 */
class SaveTask extends Action
{
    public function handle(Task|TaskDecorator $task): Task|TaskDecorator
    {
        $real_task = $task instanceof TaskDecorator ? $task->model : $task;

        Gate::authorize('save', $real_task);

        $task->save();

        TaskCreated::dispatchIf($task->wasRecentlyCreated, $real_task);
        TaskUpdated::dispatchIf(!$task->wasRecentlyCreated, $real_task);
        TaskSaved::dispatch($real_task);

        return $task;
    }
}
