<?php

namespace Tricks\MediaLibraryOverrides\Listeners;

use Spatie\Image\Image;
use Spatie\MediaLibrary\Conversions\Events\ConversionHasBeenCompletedEvent;
use Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAddedEvent;
use Tricks\MediaLibraryOverrides\Data\ImageDimensionData;

class ImageDimensionListener
{
    public function handle(MediaHasBeenAddedEvent|ConversionHasBeenCompletedEvent $event): void
    {
        if ($event->media->type !== 'image') {
            return;
        }
        $conversion = '';
        if ($event instanceof ConversionHasBeenCompletedEvent) {
            $conversion = $event->conversion->getName();
        }

        $image = Image::load($event->media->getPath($conversion));

        $event->media->setCustomProperty(
            'dimension-'.$conversion,
            new ImageDimensionData(
                width: $image->getWidth(),
                height: $image->getHeight()
            )
        );
        $event->media->save();
    }
}
