<?php

namespace DefStudio\GameEngine\Actions\Maps;

use DefStudio\Actions\Action;
use DefStudio\GameEngine\Models\Map;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Events\Maps\MapSaved;
use DefStudio\GameEngine\Events\Maps\MapCreated;
use DefStudio\GameEngine\Events\Maps\MapUpdated;

/**
 * @method static Map run(Map $map)
 */
class SaveMap extends Action
{
    public function handle(Map $map): Map
    {
        Gate::authorize('save', $map);

        $map->save();

        MapCreated::dispatchIf($map->wasRecentlyCreated, $map);
        MapUpdated::dispatchIf(!$map->wasRecentlyCreated, $map);
        MapSaved::dispatch($map);

        return $map;
    }
}
