<?php

namespace DefStudio\GameEngine\Actions\Stories;

use DefStudio\Actions\Action;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\Story;
use DefStudio\GameEngine\Events\Stories\StorySaved;
use DefStudio\GameEngine\Events\Stories\StoryCreated;
use DefStudio\GameEngine\Events\Stories\StoryUpdated;

/**
 * @method static Story run(Story $story)
 */
class SaveStory extends Action
{
    public function handle(Story $story): Story
    {
        Gate::authorize('save', $story);

        $story->organization_id ??= game_engine()->user()->current_organization_id;
        $story->save();

        StoryCreated::dispatchIf($story->wasRecentlyCreated, $story);
        StoryUpdated::dispatchIf(!$story->wasRecentlyCreated, $story);
        StorySaved::dispatch($story);

        return $story;
    }
}
