<?php

namespace Workbench\App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Str;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
use Workbench\App\Events\MediaChange;
use Workbench\App\Events\MediaDestroyed;
use Workbench\App\Events\MediaStored;
use Zoomyboy\MedialibraryHelper\DefersUploads;

class Post extends Model implements HasMedia
{
    use InteractsWithMedia;
    use DefersUploads;

    public $guarded = [];

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('defaultSingleFile')->maxWidth(fn () => 250)->singleFile();
        $this->addMediaCollection('singleJpegFile')->convert(fn () => 'jpg')->singleFile();

        $this->addMediaCollection('conversionsWithDefault')
            ->singleFile()
            ->withFallback(fn ($parent) => ['default.jpg', 'public'])
            ->registerMediaConversions(function () {
                $this->addMediaConversion('tiny')->width(200)->height(200);
            });

        $this->addMediaCollection('images')->after(fn ($model) => Event::dispatch(new MediaChange($model)));

        $this->addMediaCollection('singleForced')->singleFile()->forceFileName(function ($model, $name) {
            return $name . ' ' . now()->format('Y-m-d');
        });

        $this->addMediaCollection('multipleForced')->forceFileName(function ($model, $name) {
            return $name . ' ' . now()->format('Y-m-d');
        });

        $this->addMediaCollection('singleStoringHook')->singleFile()->storing(function ($adder, $fileName) {
            return $adder->withCustomProperties([
                'use' => 'AAA',
                'ttt' => pathinfo($fileName, PATHINFO_FILENAME),
            ]);
        });

        $this->addMediaCollection('singleWithEvent')->singleFile()->stored(function (Media $media) {
            Event::dispatch(new MediaStored($media));
        })
            ->destroyed(fn ($model) => Event::dispatch(new MediaDestroyed($model)))
            ->after(fn ($model) => Event::dispatch(new MediaChange($model)));

        $this->addMediaCollection('multipleFilesWithEvent')->stored(function (Media $media) {
            Event::dispatch(new MediaStored($media));
        });

        $this->addMediaCollection('multipleProperties')->singleFile()->withDefaultProperties(fn ($path) => [
            'test' => Str::camel($path),
        ])->withPropertyValidation(fn ($path) => [
            'test' => 'string|max:10',
        ])
            ->after(fn ($model) => Event::dispatch(new MediaChange($model)));
    }
}