<?php

namespace DefStudio\GameEngine\Actions\Awards;

use DefStudio\Actions\Action;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\Award;
use DefStudio\GameEngine\Events\Awards\AwardSaved;
use DefStudio\GameEngine\Events\Awards\AwardCreated;
use DefStudio\GameEngine\Events\Awards\AwardUpdated;

/**
 * @method static Award run(Award $award)
 */
class SaveAward extends Action
{
    public function handle(Award $award): Award
    {
        Gate::authorize('save', $award);

        $award->save();

        AwardCreated::dispatchIf($award->wasRecentlyCreated, $award);
        AwardUpdated::dispatchIf(!$award->wasRecentlyCreated, $award);
        AwardSaved::dispatch($award);

        return $award;
    }
}
