<?php

namespace App\Traits;

use Illuminate\Support\Str;
use Spatie\MediaLibrary\MediaCollections\Models\Collections\MediaCollection;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

trait WithMediaHandler
{
    public function mapMediaCollection(MediaCollection $mediaCollection)
    {
        return $mediaCollection->map(fn ($media) => [
            'id' => $media->id,
            'extension' => pathinfo($media->file_name, PATHINFO_EXTENSION),
            'temporaryUrl' => $media->getFullUrl(),
            'name' => Str::limit($media->file_name, 15),
            'size' => $media->size,
            'tmpFilename' => $media->getPath(),
        ])->toArray();
    }

    protected function syncMedia(array $newMedia, $model, string $collectionName)
    {
        $existingMediaIds = $model->getMedia($collectionName)->pluck('id')->toArray();

        $newMediaIds = collect($newMedia)->pluck('id')->filter()->toArray();

        $toDeleteIds = array_diff($existingMediaIds, $newMediaIds);

        foreach ($toDeleteIds as $id) {
            $media = Media::find($id);
            if ($media) {
                $media->delete();
            }
        }
    }

    protected function uploadMedia(array $mediaArray, $model, string $collectionName)
    {
        foreach ($mediaArray as $file) {
            if (isset($file['path'])) {
                $model->addMedia($file['path'])
                    ->preservingOriginal()
                    ->toMediaCollection($collectionName);
            }
        }
    }
}
