<?php

namespace DefStudio\GameEngine\Actions\Missions;

use DefStudio\Actions\Action;
use DefStudio\GameEngine\Models\Map;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\Mission;
use DefStudio\GameEngine\Events\Missions\MissionSaved;
use DefStudio\GameEngine\Events\Missions\MissionCreated;

/**
 * @method static Mission run(Map $parent_map, Mission $mission = null)
 */
class CreateMission extends Action
{
    public function handle(Map $parent_map, Mission $mission = null): Mission
    {
        $mission ??= $parent_map->missions()->make([
            'title' => __('New Mission'),
        ]);

        Gate::authorize('create', $mission);

        $mission->save();

        MissionCreated::dispatch($mission, $parent_map);
        MissionSaved::dispatch($mission);

        return $mission;
    }
}
