<?php

namespace Zoomyboy\MedialibraryHelper;

class CollectionExtension
{
    public function forceFileName()
    {
        return fn ($callback) => $this->registerCustomCallback('forceFileName', $callback);
    }

    public function storing()
    {
        return fn ($callback) => $this->registerCustomCallback('storing', $callback);
    }

    public function destroyed()
    {
        return fn ($callback) => $this->registerCustomCallback('destroyed', $callback);
    }

    public function convert()
    {
        return fn ($callback) => $this->registerCustomCallback('convert', $callback);
    }

    public function after()
    {
        return fn ($callback) => $this->registerCustomCallback('after', $callback);
    }

    public function withDefaultProperties()
    {
        return fn ($callback) => $this->registerCustomCallback('withDefaultProperties', $callback);
    }

    public function stored()
    {
        return fn ($callback) => $this->registerCustomCallback('stored', $callback);
    }

    public function withPropertyValidation()
    {
        return fn ($callback) => $this->registerCustomCallback('withPropertyValidation', $callback);
    }

    public function withFallback()
    {
        return fn ($callback) => $this->registerCustomCallback('withFallback', $callback);
    }

    public function maxWidth()
    {
        return fn ($callback) => $this->registerCustomCallback('maxWidth', $callback);
    }

    public function runCallback()
    {
        return function (string $callback, ...$parameters) {
            $this->setDefaultCustomCallbacks();

            return call_user_func($this->customCallbacks->get($callback), ...$parameters);
        };
    }

    public function registerCustomCallback()
    {
        return function (string $name, callable $callback) {
            $this->setDefaultCustomCallbacks();
            $this->customCallbacks->put($name, $callback);

            return $this;
        };
    }

    protected function setDefaultCustomCallbacks()
    {
        return function () {
            if (property_exists($this, 'customCallbacks')) {
                return;
            }
            $this->convertTo = null;
            $this->customCallbacks = collect([
                'forceFileName' => fn ($model, $name) => $name,
                'convert' => fn ($extension) => $extension,
                'maxWidth' => fn ($size) => null,
                'stored' => fn ($event) => true,
                'after' => fn ($event) => true,
                'destroyed' => fn ($event) => true,
                'storing' => fn ($adder, $name) => $adder,
                'withDefaultProperties' => fn ($path) => [],
                'withPropertyValidation' => fn ($path) => [],
                'withFallback' => fn ($parent) => null,
            ]);
        };
    }
}
