<?php

namespace DefStudio\GameEngine\Actions\Tasks;

use DefStudio\Actions\Action;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\Task;
use DefStudio\GameEngine\Events\Tasks\TaskDeleted;
use DefStudio\GameEngine\Events\Tasks\DeletingTask;
use DefStudio\GameEngine\Decorators\Tasks\TaskDecorator;

class DeleteTask extends Action
{
    public function handle(Task|TaskDecorator $task): void
    {
        Gate::authorize('delete', $task);

        DB::transaction(function() use ($task): void {
            $task = $task->decorate();

            DeletingTask::dispatch($task->model);

            $task->delete();

            TaskDeleted::dispatch($task->model);
        });
    }
}
