<?php

namespace DefStudio\GameEngine\Actions\Storytellings;

use DefStudio\Actions\Action;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\Storytelling;
use DefStudio\GameEngine\Events\Storytellings\StorytellingSaved;
use DefStudio\GameEngine\Events\Storytellings\StorytellingCreated;
use DefStudio\GameEngine\Events\Storytellings\StorytellingUpdated;

/**
 * @method static Storytelling run(Storytelling $storytelling)
 */
class SaveStorytelling extends Action
{
    public function handle(Storytelling $storytelling): Storytelling
    {
        Gate::authorize('save', $storytelling);

        $storytelling->save();

        StorytellingCreated::dispatchIf($storytelling->wasRecentlyCreated, $storytelling);
        StorytellingUpdated::dispatchIf(!$storytelling->wasRecentlyCreated, $storytelling);
        StorytellingSaved::dispatch($storytelling);

        return $storytelling;
    }
}
