<?php

namespace App\Support\Media;

use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\MediaCollections\Models\Media;

class MediaPresenter
{
    /**
     * @return list<array{id: int, url: string, thumb_url: string}>
     */
    public static function collection(HasMedia $model, string $collectionName): array
    {
        return $model->getMedia($collectionName)
            ->map(fn (Media $media) => self::item($media))
            ->values()
            ->all();
    }

    /**
     * @return array{id: int, url: string, thumb_url: string}|null
     */
    public static function first(HasMedia $model, string $collectionName): ?array
    {
        $media = $model->getFirstMedia($collectionName);

        return $media ? self::item($media) : null;
    }

    /**
     * @return array{id: int, url: string, thumb_url: string}
     */
    public static function item(Media $media): array
    {
        return [
            'id' => $media->id,
            'url' => $media->getUrl(),
            'thumb_url' => $media->hasGeneratedConversion('thumb')
                ? $media->getUrl('thumb')
                : $media->getUrl(),
        ];
    }
}
