<?php

namespace Tricks\LaravelTools\Nova\Fields;

use Illuminate\Http\Request;
use Laravel\Nova\Http\Requests\NovaRequest;

class File extends \Laravel\Nova\Fields\File
{
    /**
     * @param  (callable(NovaRequest, object, string, string, ?string, ?string):(mixed))|null  $storageCallback
     */
    public function __construct($name, $attribute = null, $disk = null, $storageCallback = null)
    {
        parent::__construct($name, $attribute, $disk, $storageCallback);
        $this->store(function (Request $request, $model) {
            $media = $model->addMedia($request->file($this->attribute))->toMediaCollection($this->attribute);
            $model->clearMediaCollectionExcept($this->attribute, $media);

            return true;
        });

        /** @phpstan-ignore  method.nonObject */
        $this->resolveUsing(fn ($value, $resource, $attribute) => $resource->getFirstMedia($attribute)?->file_name);
        /** @phpstan-ignore  method.nonObject */
        $this->displayUsing(fn ($value, $resource, $attribute) => $this->value = $resource->getFirstMedia($attribute));

        $this->deletable(false);
    }
}
