<?php

namespace Zoomyboy\MedialibraryHelper;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class OrderController
{
    use AuthorizesRequests;

    public function __invoke(Request $request, $parentModel, int $parentId, string $collectionName)
    {
        $mediaCount = collect($request->order)->map(function ($media) {
            $media = Media::findOrFail($media);

            return $media->model_id.'_'.$media->model_type;
        })->unique()->count();

        if (1 !== $mediaCount) {
            throw ValidationException::withMessages(['order' => 'Sortierung von verschiedenen Medien nicht möglich.']);
        }

        $model = app('media-library-helpers')->get($parentModel);
        $model = $model::find($parentId);
        $this->authorize('listMedia', [$model, $collectionName]);

        Media::setNewOrder($request->order);

        $model->getMediaCollection($collectionName)->runCallback('after', $model->fresh());

        return MediaData::collection($model->getMedia($collectionName));
    }
}
