<?php

declare(strict_types=1);

namespace Tricks\NovaTools\Traits;

use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use RuntimeException;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

trait StoresMediaLibrary
{
    public function initMediaLibrary(): void
    {
        $this->store(function (Request $request, $model): true {
            if ($model instanceof HasMedia === false) {
                throw new RuntimeException('The given model does not implements the HasMedia interface.');
            }
            $file = $request->file($this->attribute);
            if ($file instanceof UploadedFile === false) {
                throw new RuntimeException('The given file is not an instance of UploadedFile');
            }
            $media = $model->addMedia($file)->toMediaCollection($this->attribute);
            $model->clearMediaCollectionExcept($this->attribute, [$media]);

            return true;
        });

        $this->resolveUsing(function ($value, $resource, $attribute): ?string {
            if (is_null($attribute)) {
                return null;
            }
            if ($resource instanceof HasMedia === false) {
                throw new RuntimeException('The given model does not implements the HasMedia interface.');
            }
            $media = $resource->getMedia($attribute)->first();
            if ($media instanceof Media) {
                return $media->file_name;
            }

            return null;
        });

        $this->displayUsing(function ($value, $resource, $attribute): void {
            if ($resource instanceof HasMedia === false) {
                throw new RuntimeException('The given model does not implements the HasMedia interface.');
            }
            $this->value = $resource->getMedia($attribute)->first();
        });
    }
}
