<?php

/** @noinspection PhpUnhandledExceptionInspection */

namespace DefStudio\GameEngine\Actions\Tasks;

use DefStudio\Actions\Action;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Gate;
use DefStudio\GameEngine\Models\Task;
use DefStudio\GameEngine\Enums\MediaCollection;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use DefStudio\GameEngine\Decorators\Tasks\TaskDecorator;

/**
 * @method static Media run(Task|TaskDecorator $task, UploadedFile $asset_image_file, MediaCollection|string $collection_name = null)
 */
class StoreAssetImage extends Action
{
    public function handle(Task|TaskDecorator $task, UploadedFile $asset_image_file, MediaCollection|string $collection_name = null): Media
    {
        $real_task = $task instanceof TaskDecorator ? $task->model : $task;

        Gate::authorize('update', $real_task);

        if ($collection_name instanceof MediaCollection) {
            $collection_name = $collection_name->name;
        }

        return $real_task->addMedia($asset_image_file)
            ->toMediaCollection($collection_name ?? MediaCollection::assets->name);
    }
}
