<?php

declare(strict_types=1);

namespace Tricks\NovaTools\Nova\Fields;

use RuntimeException;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Tricks\NovaTools\Traits\StoresMediaLibrary;

final class Image extends \Laravel\Nova\Fields\Image
{
    use StoresMediaLibrary;

    public $deletable = false;

    public $acceptedTypes = 'image/*';

    public function __construct(
        string $name,
        string $attribute,
    ) {
        parent::__construct($name, $attribute);

        $this->initMediaLibrary();

        $getFirstMediaUrlCallback = function (mixed $value, ?string $disk, mixed $resource): ?string {
            if ($resource instanceof HasMedia === false) {
                throw new RuntimeException('The given resource does not implements the HasMedia interface.');
            }
            $media = $resource->getMedia($this->attribute)->first();

            if ($media instanceof Media) {
                return $media->getUrl();
            }

            return null;
        };

        $this->thumbnail($getFirstMediaUrlCallback)
            ->preview($getFirstMediaUrlCallback);
    }
}
