<?php

namespace DefStudio\GameEngine\Database\Factories\Concerns;

use Livewire\TemporaryUploadedFile;
use Illuminate\Database\Eloquent\Model;
use DefStudio\GameEngine\Enums\MediaCollection;

trait HasMedia
{
    public function with_media(MediaCollection|string $media_collection, string $path = null): self
    {
        if ($media_collection instanceof MediaCollection) {
            $media_collection = $media_collection->name;
        }

        return $this->afterCreating(function(Model&\Spatie\MediaLibrary\HasMedia $model) use ($media_collection, $path) {
            $file = $path
                ? TemporaryUploadedFile::fake()->createWithContent(
                    str($path)->afterLast(DIRECTORY_SEPARATOR)->toString(),
                    file_get_contents($path),
                )
                : TemporaryUploadedFile::fake()->image('image.jpg');
            $model->addMedia($file)
                ->toMediaCollection($media_collection);
        });
    }
}
