<?php

namespace Zoomyboy\MedialibraryHelper;

use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Storage;

trait DefersUploads
{
    public function setDeferredUploads(array $uploads): void
    {
        if (array_key_exists('collection_name', $uploads)) {
            $uploads = [$uploads];
        }

        foreach ($uploads as $upload) {
            $this->runMediaUploadForSingleFile($upload);
        }
    }

    protected function runMediaUploadForSingleFile(array $fileData): void
    {
        $collection = $this->getMediaCollection($fileData['collection_name']);

        $file = new MediaFile($this->storage()->path($fileData['file_name']));
        $file->setBasename($collection->runCallback('forceFileName', $this, $file->getBasename()));

        $adder = $this->addMediaFromDisk('media-library/' . $fileData['file_name'],  config('media-library.temp_disk'))
            ->usingName($file->getBasename())
            ->usingFileName($file->getFilename())
            ->withCustomProperties($collection->runCallback('withDefaultProperties', $file->getFilename()));

        tap(
            $collection->runCallback('storing', $adder, $file->getFilename())->toMediaCollection($collection->name),
            fn ($media) => $collection->runCallback('stored', $media)
        );

        $collection->runCallback('after', $this);
    }

    protected function storage(): FilesystemAdapter
    {
        return Storage::disk(config('media-library.temp_disk'));
    }
}
